dsh-jira-work-overview 0.16.6 → 0.16.7

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/CHANGELOG.md CHANGED
@@ -4,6 +4,34 @@ All notable changes to **dsh-jira-work-overview** are documented here.
4
4
 
5
5
  The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html). The first 25 releases were built in a single day, so the dates are real but the cadence was not: each entry lists what changed, not how long it took.
6
6
 
7
+ ## [Unreleased]
8
+
9
+ ## [0.16.7] - 2026-12-01
10
+
11
+ ### Fixed
12
+
13
+ - **长时间挂起 / Mac 合盖后再打开,面板列表停在旧数据上(角标却在动)。** 列表只在「首次打开 /
14
+ 显式操作 / watch 发现变化」时重拉,而 watch 的自动刷新还要求「之前已经有未读」(`before > 0`),
15
+ 清过角标后的第一条变化不会刷新列表;入口按钮打开时看到已有数据也直接显示,不做任何重拉。于是
16
+ 新任务能进未读角标、能弹系统通知,列表却只能手动点「刷新」。
17
+ 现在:① 打开面板 / 窗口从隐藏或睡眠恢复(`visibilitychange` / `focus` / `pageshow`)时,载荷超过
18
+ 60 秒或还有未读变化就重拉;② 面板开着时 watch 一出现新变化就重拉(不再要求之前已有未读);
19
+ ③ watch 长轮询加了客户端超时(40 秒),睡眠里断掉的请求会被主动 abort 并重连,醒来后角标不会卡死。
20
+ 新增离线套件 `test/dsh-jira-resume.mjs` 覆盖这几条(含「关闭 2 分钟后重开能看到新任务」)。
21
+
22
+ ### Changed
23
+
24
+ - **面板每次加载少打 3 个 Jira 请求。** 面板固定 `--limit=0` 把结果翻到底,原来还要再打两次
25
+ `approximate-count`(总数 + 每个项目的总数)和一次 `GET /rest/agile/1.0/board/{id}/sprint`——串行排在
26
+ 翻页后面。现在翻页到底时总数与项目数直接用已取回的条目本地统计,count 只在被 `--limit=` /
27
+ 5000 条安全上限 / `timeoutMs` 截断时才打;活跃迭代的请求提前到与翻页并行。实测(本机到站点,
28
+ 350 条 4 页)请求数 7 → 4,面板整条路径耗时约 -35%(桩基准 819ms → 516ms @100ms/请求)。
29
+ - **首屏先画第一页,剩下的在后台补。** 面板在「还没有数据」时打开会先发一次 `--limit=100 --preview`
30
+ (host 只取一页、不查 `approximate-count`、不查活跃迭代,约 1 个往返),先把这 100 行画出来,
31
+ 随后再拉全量替换——等待时不再是空面板转圈,而是「先读着,数字和后面的行随后补齐」。
32
+ `--preview` 载荷里 `total` / `projectTotals` 为 `null`、`hasMore` 恒为 `true`,界面等全量那份再显示数字;
33
+ 首屏失败不影响最终结果(全量那份给出真正的错误)。
34
+
7
35
  ## [0.16.6] - 2026-11-26
8
36
 
9
37
  ### Changed
package/README.md CHANGED
@@ -38,7 +38,7 @@ Show **your** Jira work items — with their real workflow status — inside [De
38
38
  DSH installs plugins from an **installation spec** — anything `pnpm add` accepts (registry package name, git URL, tarball, absolute path). Pick one:
39
39
 
40
40
  ```bash
41
- # 1) from the npm registry (published since 0.14.0; pin a version with @0.16.6)
41
+ # 1) from the npm registry (published since 0.14.0; pin a version with @0.16.7)
42
42
  plugin_manager install_bundle(target="dsh-jira-work-overview")
43
43
 
44
44
  # 2) straight from GitHub (no npm publishing needed)
@@ -94,7 +94,8 @@ Prefer files? Add an override row to your profile's `cordis.patch.yml` (this is
94
94
  - **Search**: the header magnifier expands in place into a field that slides out to the left; type a keyword or an issue key and press **Enter**. The query runs against all of Jira (not only your issues); matches are grouped by sprint like your own list, with the same project tabs / status filter / total. Losing focus (or **Esc**) collapses the field back to the button and keeps an unsubmitted draft; a submitted query clears the field and keeps the results, and `×` clears the search to return to your work.
95
95
 
96
96
  <img src="docs/images/panel-search.png" width="1040" alt="A search for 'checkout' inside the panel: the header field is open, the subtitle reads 'Search: checkout 4 items', and the hits are grouped by sprint with their epic line and the same filters as the work list">
97
- - The header shows the **accurate total** for the current project + status, straight from Jira's `approximate-count`.
97
+ - **The first page paints first**: opening the panel with no data at hand fetches page 1 (`--preview`: one round trip, no counts, no sprint lookup) and draws those rows, then the full load replaces them in the background — you read the list while the rest arrives.
98
+ - The header shows the **accurate total** for the current project + status: when pagination runs to the end it is the fetched row count (no extra request); only a truncated fetch (`--limit=`, the 5000-item safety net or `timeoutMs`) asks Jira's `approximate-count`.
98
99
  - Click a **status chip** on any row to move the issue; the list reloads. **Esc** closes the top-most layer (status menu → configure dialog → panel).
99
100
  - The list is **virtualized**: thousands of rows scroll smoothly because only the visible ones are in the DOM.
100
101
  - **Plan at the end of a row** (the `☰ 计划` chip) opens a *planning* conversation for that issue in the
@@ -200,6 +201,8 @@ The host polls `assignee = currentUser() AND statusCategory != Done` every `watc
200
201
 
201
202
  A status **you** changed — from the panel dropdown or `jira_transition` — is not news: the write records the expected `from → to` and the next poll silently advances its baseline instead of raising a notification, an unread badge or a banner entry. The match is on that exact pair, so a colleague changing the same issue to something else still notifies. Notifications use `osascript` on macOS, a PowerShell Toast on Windows, and `notify-send` elsewhere — silently degrading if the platform refuses.
202
203
 
204
+ The list also re-fetches when it may be stale: opening the panel after it has been closed for more than a minute (or while an unread change is pending), and returning to a visible window after sleep / hiding (`visibilitychange` / `focus` / `pageshow`). The badge moving no longer leaves the list behind, and the long poll has a client-side timeout so a request killed by sleep reconnects instead of freezing the badge.
205
+
203
206
  ## Configuration reference
204
207
 
205
208
  | Key | Default | Meaning |
@@ -267,7 +270,7 @@ Behind a corporate proxy on Windows, DSH needs the proxy env vars it was started
267
270
 
268
271
  ## Versions and upgrades
269
272
 
270
- The current version is **0.16.6** (2026-11-26). The changelog records 40 versions (from 0.1.0); GitHub carries **15 tags / releases** (0.13.0 → 0.16.6), and **0.13.4 was the first public release** — the earlier 0.1.0–0.12.0 exist only in `CHANGELOG.md` and the project notes, with no commit or tag behind them, so "an older version" means **0.13.0 or later**. Every release is described in [CHANGELOG.md](CHANGELOG.md).
273
+ The current version is **0.16.7** (2026-12-01). The changelog records 41 versions (from 0.1.0); GitHub carries **16 tags / releases** (0.13.0 → 0.16.7), and **0.13.4 was the first public release** — the earlier 0.1.0–0.12.0 exist only in `CHANGELOG.md` and the project notes, with no commit or tag behind them, so "an older version" means **0.13.0 or later**. Every release is described in [CHANGELOG.md](CHANGELOG.md).
271
274
 
272
275
  ### Why people still install older versions
273
276
 
@@ -309,6 +312,7 @@ The current version is **0.16.6** (2026-11-26). The changelog records 40 version
309
312
  | 0.16.4 | 2026-11-23 | **fix** | on a fresh profile, filling email + token + site URL and clicking only **Save & verify** left the URL unsaved, so the panel always said there was no site URL; the panel now also reloads automatically after a successful save |
310
313
  | 0.16.5 | 2026-11-24 | feature | **nothing configured shows a form, not an error**: the panel body is the Connect Jira form (site URL / email / API token) in the old failure slot, saved fields can stay empty, and the list reloads once Jira accepts the pair |
311
314
  | 0.16.6 | 2026-11-26 | feature | **`☰ Plan` works on an unlinked project too**: the planning conversation lands in the project's workspace when there is one and in DSH's default Workspace otherwise (resolved through `workspaces.initializeDefault()` client-side and `workspaceController.initializeDefault()` host-side); only when neither resolves does it fail, with copy that says so |
315
+ | 0.16.7 | 2026-12-01 | **fix + perf** | after a long suspend / lid close the panel kept showing the old list (resume + watch refresh, new `test/dsh-jira-resume.mjs`); the panel path now makes 3 fewer Jira requests (local totals, sprint lookup in parallel); **the first page paints first**, the full load replaces it in the background |
312
316
 
313
317
  > 0.1.0–0.12.0 all happened on 2026-11-18; tags and GitHub Releases start at 0.13.0.
314
318
  > To install an older version: `plugin_manager install_bundle(target="github:EagleSoap/dsh-jira-work-overview#v0.13.2")`, or pin the npm version with `target="dsh-jira-work-overview@0.14.0"` (the earliest version on npm is 0.14.0).
package/README.zh.md CHANGED
@@ -21,7 +21,7 @@
21
21
  DSH 用**安装 spec** 装插件 —— 凡是 `pnpm add` 能吃的写法都行(registry 包名、git 地址、tarball、绝对路径)。选一个:
22
22
 
23
23
  ```bash
24
- # 1) 从 npm 装(0.14.0 起已发布;要钉版本就在后面写 @0.16.6)
24
+ # 1) 从 npm 装(0.14.0 起已发布;要钉版本就在后面写 @0.16.7)
25
25
  plugin_manager install_bundle(target="dsh-jira-work-overview")
26
26
 
27
27
  # 2) 直接从 GitHub 装(不需要 npm 发布)
@@ -259,11 +259,17 @@ profile 里装了 `deepseek-ai/dsh-plan-mode` 就用它的 `section` 当规划
259
259
  - 上一版(0.11.0)的「渐进式渲染」(`RENDER_FIRST = 80` / `RENDER_STEP = 120` / 「正在渲染 N / M 行」)**已整套删除**,
260
260
  换筛选 / 换 tab / 刷新后不会再有「分批画」的残留状态,滚动位置在切筛选、换 tab、刷新时重置到顶部。
261
261
 
262
+ ### 首屏先画第一页
263
+
264
+ - 还没有数据时打开面板,会先请求第一页(`--limit=100 --preview`:host 只取一页,不查总数、不查活跃迭代,
265
+ 约一个往返),先把这 100 行画出来;随后全量那份替换它——等待时不再是空面板转圈。
266
+ - 首屏那份的「共 N 项」暂时空着(`total` 为 `null`),等全量回来后补上;首屏失败不影响最终结果。
267
+
262
268
  ### 「共 N 项」是准确总数,不是页内条数
263
269
 
264
- - **标题下面**的副标题会显示「**共 N 项**」(有状态筛选时再拼一句「· 状态 <名字>」),这个数字来自 Jira 的
265
- `POST /rest/api/3/search/approximate-count`(只回一个 `count`,不拉数据)——实测与「自己翻页把结果全拉完」完全一致:
266
- 未完成 9 = 9、全部 332 = 332(4 页)。
270
+ - **标题下面**的副标题会显示「**共 N 项**」(有状态筛选时再拼一句「· 状态 <名字>」)。翻页**拉到底**时这个数字就是
271
+ 已取回的条数(本地统计,不再多打请求);只有翻页被 `--limit=` / 5000 条安全上限 / `timeoutMs` **截断**时,才用 Jira 的
272
+ `POST /rest/api/3/search/approximate-count`(只回一个 `count`,不拉数据)补一个准确总数——两条路径都与「把结果全拉完」一致。
267
273
  - 数字随**当前筛选与当前项目 tab** 变:选「全部项目」时是整个范围(含已完成)的总数;选了某个项目 tab 就显示该项目
268
274
  在当前范围下的总数(每个项目一次 count,最多统计 8 个项目,超过就只给总数)。
269
275
  - **拿不到就不显示**(当年查询失败、count 端点不可用时副标题里没有数字,只留状态筛选那半句),宁可空着也不给一个会跳的数。
@@ -283,6 +289,10 @@ Jira Cloud **没有**给第三方 issue 事件的 websocket / SSE 长连接(
283
289
  同事把同一个 issue 改成别的状态照样通知;写失败会立刻撤掉这份期望,不会吞掉之后别人的真变化。
284
290
  - **面板角标**:入口按钮右上角显示未读条数;面板顶部出现「N 项新变化」横幅(列出最近几条,
285
291
  如 `APP-4018 In Review → IN QA`)和「标记已读」按钮;面板开着时又来新变化会自动刷新列表。
292
+ - **重新打开 / 从挂起恢复也会重拉**:Mac 合盖、把窗口藏起来很久再打开时,载荷超过 60 秒(或还有
293
+ 未读变化)就先重拉一次;窗口重新可见(`visibilitychange` / `focus` / `pageshow`)同样按这个
294
+ 新鲜度判断。不会再出现「角标在动、列表还是旧的、只能手动刷新」——长轮询只负责通知,列表自己
295
+ 也要跟上。
286
296
  - **通道**:Host 在 `ctx.get('connection').fetch` 上注册四条精确路由——`/api/jira-work-overview/state`
287
297
  (GET = 状态,支持 `?wait=25000` 长轮询;POST = 标记已读)、`/api/jira-work-overview/transition`
288
298
  (GET `?key=…` = 可用流转;POST `{key, transitionId}` = 改状态)、`/api/jira-work-overview/credential`
@@ -520,7 +530,7 @@ Zed(`zed`)、Sublime Text(`subl`)、gedit(`gedit`)——**找到可
520
530
 
521
531
  ## 版本与升级
522
532
 
523
- 当前版本 **0.16.6**(2026-11-26)。`CHANGELOG.md` 记了 40 个版本(0.1.0 起),GitHub 上有 **15 个 tag / Release**(0.13.0 → 0.16.6),**0.13.4 是第一个公开版本**——更早的 0.1.0–0.12.0 只存在于 `CHANGELOG.md` 与项目记录里,没有对应的提交与 tag,所以「以前的版本」= **0.13.0 及以后**。逐版的完整说明见 [CHANGELOG.md](CHANGELOG.md)。
533
+ 当前版本 **0.16.7**(2026-12-01)。`CHANGELOG.md` 记了 41 个版本(0.1.0 起),GitHub 上有 **16 个 tag / Release**(0.13.0 → 0.16.7),**0.13.4 是第一个公开版本**——更早的 0.1.0–0.12.0 只存在于 `CHANGELOG.md` 与项目记录里,没有对应的提交与 tag,所以「以前的版本」= **0.13.0 及以后**。逐版的完整说明见 [CHANGELOG.md](CHANGELOG.md)。
524
534
 
525
535
  ### 为什么有人还在装以前的版本
526
536
 
@@ -562,6 +572,7 @@ Zed(`zed`)、Sublime Text(`subl`)、gedit(`gedit`)——**找到可
562
572
  | 0.16.4 | 2026-11-23 | **修复** | 全新 profile 上把邮箱、令牌、站点地址一起填好、只点「保存并验证」时地址没落盘,面板一直说没配站点地址;配置保存成功后还会自动重拉列表 |
563
573
  | 0.16.5 | 2026-11-24 | 功能 | **没配置时给的是表单而不是报错**:面板直接把「连接 Jira」表单(服务地址 / 邮箱 / API token)放在原来的失败位置,已保存的字段可留空,连接成功即重拉列表 |
564
574
  | 0.16.6 | 2026-11-26 | 功能 | **项目没绑工作区也能点「计划」**:绑了建在项目的工作区,没绑落到 DSH 的默认工作区(client 走 `workspaces.initializeDefault()`、host 走 `workspaceController.initializeDefault()`),只有两者都取不到才报错,文案也写明是「也取不到默认工作区」 |
575
+ | 0.16.7 | 2026-12-01 | **修复 + 性能** | 挂起 / 合盖后重开面板列表停在旧数据上(补恢复重拉与 watch 刷新,新增 `test/dsh-jira-resume.mjs`);面板整条路径少打 3 个 Jira 请求(翻到底本地统计总数、活跃迭代与翻页并行);**首屏先画第一页**,全量在后台补 |
565
576
 
566
577
  > 0.1.0–0.12.0 这 15 个版本都发生在 2026-11-18 同一天;0.13.0 起才有 tag 与 Release。
567
578
  > 想装某个旧版本:`plugin_manager install_bundle(target="github:EagleSoap/dsh-jira-work-overview#v0.13.2")`,或从 npm 钉版本 `target="dsh-jira-work-overview@0.14.0"`(npm 上最早的版本是 0.14.0)。
package/client.js CHANGED
@@ -636,6 +636,8 @@ window.__ModuleLoader__.load({
636
636
  failure: null,
637
637
  scope: DEFAULT_SCOPE,
638
638
  data: null,
639
+ // 上一次成功拉回列表的时刻(毫秒)。打开面板 / 窗口恢复可见时靠它判断载荷是不是旧了。
640
+ dataAt: 0,
639
641
  collapsed: {},
640
642
  watch: null,
641
643
  // 条数不再进 snapshot:面板固定按「不限制」拉取,host 自己以 5000 条 / 50 页 / 30s 兜底。
@@ -744,6 +746,16 @@ window.__ModuleLoader__.load({
744
746
 
745
747
  const WATCH_PATH = '/api/jira-work-overview/state';
746
748
  const WATCH_WAIT_MS = 25000;
749
+ // 列表载荷的「新鲜度」:打开面板 / 窗口从挂起恢复时,超过这个年龄就先重拉一次。
750
+ // 后台 watch 长轮询只说明「有新变化」,自己不替列表重拉;Mac 合盖 / 窗口藏起来时
751
+ // 定时器还会被冻结,回来时列表可能停在睡前那一份。
752
+ const DATA_STALE_MS = 60 * 1000;
753
+ // 长轮询的客户端兜底:Host 侧最长等 25s,网络在睡眠里断掉时 fetch 可能一直挂着,
754
+ // 超时就主动 abort 让循环重连(否则醒来后角标再也不动)。
755
+ const WATCH_CLIENT_TIMEOUT_MS = WATCH_WAIT_MS + 15000;
756
+ // 首屏那一页的条数:与 host 的 PAGE_SIZE 一致(Jira 带 fields 时一页最多 100 条)。
757
+ // 首屏只画这一页,剩下的翻页在后台补(见 load 的两阶段)。
758
+ const PAGE_LIMIT = 100;
747
759
  // 面板里改状态走 Host 的写通道(GET 列可用流转 / POST 执行流转)。
748
760
  const TRANSITION_PATH = '/api/jira-work-overview/transition';
749
761
  // 配置页里换令牌走的通道:GET 打码状态、POST 保存/清除(Host 侧仍写同一个凭据库键)。
@@ -807,6 +819,13 @@ window.__ModuleLoader__.load({
807
819
  while (!watch.stopped) {
808
820
  const controller = typeof AbortController === 'function' ? new AbortController() : undefined;
809
821
  watch.controller = controller;
822
+ let timeout = null;
823
+ if (controller) {
824
+ timeout = setTimeout(() => {
825
+ try { controller.abort(); } catch { /* ignore */ }
826
+ }, WATCH_CLIENT_TIMEOUT_MS);
827
+ if (typeof timeout?.unref === 'function') timeout.unref();
828
+ }
810
829
  try {
811
830
  const response = await watchFetch(`${WATCH_PATH}?wait=${WATCH_WAIT_MS}`, {
812
831
  method: 'GET',
@@ -825,13 +844,17 @@ window.__ModuleLoader__.load({
825
844
  failures = 0;
826
845
  patchWatch({ supported: true, reason: '', error: '', failures: 0, ...(incoming ?? {}) });
827
846
  const total = incoming?.counts?.total ?? 0;
828
- // 面板开着、且这次真的多了未读变化,就顺手把列表刷成新的。
829
- if (snapshot.open && before > 0 && total > before && !snapshot.loading) load(snapshot.scope);
847
+ // 面板开着、且这次真的多了变化,就顺手把列表刷成新的。**不要求之前已经有未读**:
848
+ // 清过角标之后的第一条(before = 0)同样得刷新,否则列表会一直停在旧数据上,
849
+ // 只有角标在动——Mac 合盖醒来 / 窗口藏一晚上再打开时最明显。
850
+ if (snapshot.open && total > before && !snapshot.loading) load(snapshot.scope);
830
851
  } catch (error) {
831
852
  if (watch.stopped || watch.controller !== controller) break;
832
853
  failures += 1;
833
854
  patchWatch({ supported: true, error: String(error?.message ?? error), failures });
834
855
  await sleep(Math.min(30000, 4000 * failures));
856
+ } finally {
857
+ if (timeout) clearTimeout(timeout);
835
858
  }
836
859
  }
837
860
  }
@@ -1071,6 +1094,29 @@ window.__ModuleLoader__.load({
1071
1094
  * ——host 会一直翻页到没有下一页,只受它自己的安全上限(5000 条 / 50 页 / 30s)约束。
1072
1095
  * 条数不再是面板的功能开关,所以这里不吃 limit 参数(「加载更多」只在 host 真截断时出现)。
1073
1096
  */
1097
+ // 面板固定发 scope(all,含已完成/已关闭);`--status=` 是单选状态筛选,空串表示不筛。
1098
+ // `--search=` 放在行尾:搜索词可能带空格,host 会一路吃到下一个 `--` 开关为止。
1099
+ function buildLine(scope, limit, preview) {
1100
+ const status = typeof snapshot.status === 'string' ? snapshot.status : '';
1101
+ const search = typeof snapshot.searchText === 'string' ? snapshot.searchText.trim() : '';
1102
+ return `/jira --json ${scope} --limit=${limit}${preview ? ' --preview' : ''}${status ? ` --status=${status}` : ''} --lang=${currentLanguage()}${search ? ` --search=${search}` : ''}`;
1103
+ }
1104
+
1105
+ /** 发一行命令并把结构化载荷解析出来;通道失败 / 命令失败按面板口径抛错。 */
1106
+ async function executeLine(sessionId, line, signal) {
1107
+ const commands = resolveCommands();
1108
+ const result = await commands.execute(sessionId, line, [], signal);
1109
+ if (!result || result.ok !== true) {
1110
+ const code = result?.error?.code ?? '-';
1111
+ const message = result?.error?.message ?? '-';
1112
+ throw new Error(`${t('commandFailed')}: ${code}: ${message}`);
1113
+ }
1114
+ if (result.value === undefined) throw new Error(t('unknownCommand'));
1115
+ const outcome = result.value.result;
1116
+ if (!outcome || outcome.kind !== 'success') throw new Error(outcome?.text || t('commandFailed'));
1117
+ return JSON.parse(outcome.text);
1118
+ }
1119
+
1074
1120
  async function load(scope) {
1075
1121
  const next = scope || snapshot.scope;
1076
1122
  const commands = resolveCommands();
@@ -1088,32 +1134,32 @@ window.__ModuleLoader__.load({
1088
1134
  const seq = cancelLoad();
1089
1135
  const controller = typeof AbortController === 'function' ? new AbortController() : undefined;
1090
1136
  loadController = controller;
1137
+ const firstPaint = !snapshot.data && !snapshot.error && !snapshot.failure;
1091
1138
  patch({ loading: true, error: '', failure: null, scope: next });
1092
1139
  try {
1093
- // host 的 i18n 已落地:命令面也把界面语言捎过去,否则 host 渲染的文案会跟面板不一致。
1094
- // 面板固定发 scope(all,含已完成/已关闭);`--status=` 是单选状态筛选,空串表示不筛。
1095
- // `--search=` 放在行尾:搜索词可能带空格,host 会一路吃到下一个 `--` 开关为止。
1096
- const status = typeof snapshot.status === 'string' ? snapshot.status : '';
1097
- const search = typeof snapshot.searchText === 'string' ? snapshot.searchText.trim() : '';
1098
- const line = `/jira --json ${next} --limit=0${status ? ` --status=${status}` : ''} --lang=${currentLanguage()}${search ? ` --search=${search}` : ''}`;
1099
- const result = await commands.execute(sessionId, line, [], controller?.signal);
1100
- if (seq !== loadSeq) return;
1101
- if (!result || result.ok !== true) {
1102
- const code = result?.error?.code ?? '-';
1103
- const message = result?.error?.message ?? '-';
1104
- throw new Error(`${t('commandFailed')}: ${code}: ${message}`);
1140
+ // 两阶段:首屏先要第一页(`--preview` 让 host 跳过 count 与迭代查询,只 ~1 个往返),
1141
+ // 先把 100 行画出来;随后再拉全量替换。首屏只是加速,失败就静静等全量那份。
1142
+ if (firstPaint) {
1143
+ try {
1144
+ const preview = await executeLine(sessionId, buildLine(next, PAGE_LIMIT, true), controller?.signal);
1145
+ if (seq !== loadSeq) return;
1146
+ if (preview && preview.ok !== false && Array.isArray(preview.items) && preview.items.length > 0) {
1147
+ patch({ data: preview, dataAt: Date.now(), loading: true, error: '', failure: null });
1148
+ }
1149
+ } catch {
1150
+ /* 首屏失败不改变最终结果:全量那份会给出真正的错误 */
1151
+ }
1152
+ if (seq !== loadSeq) return;
1105
1153
  }
1106
- if (result.value === undefined) throw new Error(t('unknownCommand'));
1107
- const outcome = result.value.result;
1108
- if (!outcome || outcome.kind !== 'success') throw new Error(outcome?.text || t('commandFailed'));
1109
- const data = JSON.parse(outcome.text);
1154
+ const data = await executeLine(sessionId, buildLine(next, 0, false), controller?.signal);
1155
+ if (seq !== loadSeq) return;
1110
1156
  // host 在 --json 失败时不再 throw,而是回一份形状正常的 ok:false 载荷:这里只留
1111
1157
  // error.code / message,界面按 code 给提示,不把整句报错糊在列表位置。
1112
1158
  if (data && data.ok === false) {
1113
1159
  patch({ data: null, failure: data.error ?? { code: 'unknown', message: '' }, error: '', loading: false });
1114
1160
  return;
1115
1161
  }
1116
- patch({ data, failure: null, error: '', loading: false });
1162
+ patch({ data, failure: null, error: '', loading: false, dataAt: Date.now() });
1117
1163
  } catch (error) {
1118
1164
  if (seq !== loadSeq) return; // 被新请求取代 / 主动取消:不当成错误显示
1119
1165
  patch({ error: String(error?.message ?? error), failure: null, loading: false });
@@ -1122,6 +1168,65 @@ window.__ModuleLoader__.load({
1122
1168
  }
1123
1169
  }
1124
1170
 
1171
+ /* ---------------------------------------------- 重新打开 / 从挂起恢复 */
1172
+ //
1173
+ // 列表只在「首次打开 / 显式操作 / 后台 watch 发现变化」时重拉。Mac 合盖一晚上再打开、
1174
+ // 或把窗口藏起来很久再回来时,watch 长轮询同样可能被冻结,回来只剩一份旧载荷;而入口
1175
+ // 按钮原来看到「已有数据」就直接显示,不做任何重拉——于是新任务能进角标、能弹通知,
1176
+ // 列表却一直停在睡前那一份,只能手动点「刷新」。
1177
+ //
1178
+ // 兜底两条:① 打开面板 / 窗口重新可见时,载荷超过 DATA_STALE_MS、或还有未读变化,就重拉;
1179
+ // ② 面板开着时 watch 一出现新变化就重拉(见 watchLoop)。两条都不改变「关着面板不查 Jira」。
1180
+
1181
+ function dataAge() {
1182
+ return Date.now() - Number(snapshot.dataAt ?? 0);
1183
+ }
1184
+
1185
+ /** 面板打开 / 窗口恢复可见时调用:旧了、或者有未读变化,就重拉一次。 */
1186
+ function refreshListIfStale() {
1187
+ if (!snapshot.open || snapshot.loading) return false;
1188
+ const unread = snapshot.watch?.counts?.total ?? 0;
1189
+ if (snapshot.data && !snapshot.error && unread === 0 && dataAge() < DATA_STALE_MS) return false;
1190
+ void load(snapshot.scope);
1191
+ return true;
1192
+ }
1193
+
1194
+ function startResumeRefresh(ctx) {
1195
+ const doc = typeof document !== 'undefined' ? document : undefined;
1196
+ const win = typeof window !== 'undefined' ? window : undefined;
1197
+ if (typeof doc?.addEventListener !== 'function' && typeof win?.addEventListener !== 'function') return;
1198
+ let timer = null;
1199
+ const schedule = () => {
1200
+ // 变成 hidden 的那一下不刷新;focus / pageshow / visibilitychange 可能连着来,合并成一次。
1201
+ if (doc && doc.visibilityState === 'hidden') return;
1202
+ if (timer) clearTimeout(timer);
1203
+ timer = setTimeout(() => {
1204
+ timer = null;
1205
+ refreshListIfStale();
1206
+ }, 120);
1207
+ };
1208
+ const attach = () => {
1209
+ doc?.addEventListener?.('visibilitychange', schedule);
1210
+ win?.addEventListener?.('focus', schedule);
1211
+ win?.addEventListener?.('pageshow', schedule);
1212
+ return () => {
1213
+ if (timer) clearTimeout(timer);
1214
+ doc?.removeEventListener?.('visibilitychange', schedule);
1215
+ win?.removeEventListener?.('focus', schedule);
1216
+ win?.removeEventListener?.('pageshow', schedule);
1217
+ };
1218
+ };
1219
+ if (typeof ctx?.effect === 'function') {
1220
+ try {
1221
+ ctx.effect(attach, 'jira-work-overview: resume refresh');
1222
+ return;
1223
+ } catch {
1224
+ /* 落到下面的直接挂 */
1225
+ }
1226
+ }
1227
+ attach();
1228
+ }
1229
+
1125
1230
  /* ------------------------------------------------ 项目 ↔ 工作区 */
1126
1231
  //
1127
1232
  // 一个 Jira 项目挂到一个工作区(工作区 = 一个项目目录),这样切到哪个工作区,
@@ -2178,8 +2283,9 @@ window.__ModuleLoader__.load({
2178
2283
  const open = !snapshot.open;
2179
2284
  // 计划失败提示是上一次点击的产物:收起 / 重开面板时一并清掉。
2180
2285
  patch({ open, credOpen: false, menuKey: '', filterOpen: false, autoPickedOnce: false, planError: '' });
2181
- // 打开时若还没有数据、或上次是错误(例如当时没有会话),就顺手重试一次。
2182
- if (open && (snapshot.error || !snapshot.data) && !snapshot.loading) load(snapshot.scope);
2286
+ // 打开时按「新鲜度」决定要不要重拉:没有数据 / 上次是错误 / 载荷旧了 / 还有未读变化
2287
+ // 都重拉一次(长时间挂起后重开面板,列表不能停在旧数据上)。
2288
+ if (open) refreshListIfStale();
2183
2289
  // 工作区 ↔ 项目:打开面板时按当前会话的工作区把 tab 落到关联项目上(只做这一次,之后以用户选择为准)。
2184
2290
  if (open) {
2185
2291
  const p = fetchWorkspaceLinks().then(() => adoptWorkspaceProject());
@@ -2207,7 +2313,7 @@ window.__ModuleLoader__.load({
2207
2313
  run: () => {
2208
2314
  // 打开面板,并在项目 tab 条上把候选项目标成「待关联」:点哪个项目就挂到哪个工作区。
2209
2315
  patch({ open: true, credOpen: false, menuKey: '', filterOpen: false, autoPickedOnce: false, linkTarget: workspaceId });
2210
- if (!snapshot.data && !snapshot.loading) load(snapshot.scope);
2316
+ refreshListIfStale();
2211
2317
  void fetchWorkspaceLinks(true);
2212
2318
  },
2213
2319
  };
@@ -4149,6 +4255,8 @@ window.__ModuleLoader__.load({
4149
4255
  void fetchPlanSessions();
4150
4256
 
4151
4257
  startWatchLoop(ctx);
4258
+ // 窗口从隐藏 / 睡眠里回来时重拉旧载荷(与 watch 长轮询互补:那条只保证角标和通知)。
4259
+ startResumeRefresh(ctx);
4152
4260
  },
4153
4261
  };
4154
4262
  },
package/index.js CHANGED
@@ -878,6 +878,8 @@ async function runCommand(jira, raw, signal) {
878
878
  const tokens = typeof raw === 'string' && raw.trim() ? raw.trim().split(/\s+/) : [];
879
879
  // `--json` 是给 client 面板用的:同一次查询,换成结构化输出让界面自己排版。
880
880
  const json = tokens.includes('--json');
881
+ // `--preview` 是面板首屏用的:只取第一页、不查总数/迭代,先把 100 行画出来(全量那份随后替换)。
882
+ const preview = tokens.includes('--preview');
881
883
  const limitToken = tokens.find((token) => token.startsWith('--limit='));
882
884
  const limit = limitToken ? normalizeLimit(limitToken.slice('--limit='.length), limitOf(jira.settings)) : limitOf(jira.settings);
883
885
  // 逐 token 收集剩余参数(= scope 词或自定义 JQL),同时摘掉三个开关:
@@ -890,7 +892,7 @@ async function runCommand(jira, raw, signal) {
890
892
  let search = '';
891
893
  for (let i = 0; i < tokens.length; i += 1) {
892
894
  const token = tokens[i];
893
- if (token === '--json' || token.startsWith('--limit=') || token.startsWith('--lang=')) continue;
895
+ if (token === '--json' || token === '--preview' || token.startsWith('--limit=') || token.startsWith('--lang=')) continue;
894
896
  if (token.startsWith('--status=')) {
895
897
  const parts = [token.slice('--status='.length)];
896
898
  while (i + 1 < tokens.length && !tokens[i + 1].startsWith('--')) {
@@ -922,7 +924,7 @@ async function runCommand(jira, raw, signal) {
922
924
  );
923
925
 
924
926
  try {
925
- return await runQuery(jira, { json, limit, rest, status, jql, scope, search, signal });
927
+ return await runQuery(jira, { json, limit, rest, status, jql, scope, search, preview, signal });
926
928
  } catch (error) {
927
929
  // 面板走 --json:失败也做成结构化载荷(ok:false + error.code),界面才能按类型给提示,
928
930
  // 而不是把一整句报错糊在列表位置。命令行文本输出保持原样抛出(那条命令面本来就该看到错误)。
@@ -932,7 +934,7 @@ async function runCommand(jira, raw, signal) {
932
934
  }
933
935
 
934
936
  /** 查询主体:单条 issue 或工作列表;文本 / JSON 两种输出只在这里分叉。 */
935
- async function runQuery(jira, { json, limit, rest, status, jql, scope, search, signal }) {
937
+ async function runQuery(jira, { json, limit, rest, status, jql, scope, search, preview = false, signal }) {
936
938
  if (rest && ISSUE_KEY.test(rest.toUpperCase())) {
937
939
  const key = rest.toUpperCase();
938
940
  // 单条 issue 也要带 epic 字段:详情里的关联行与列表走同一套 buildItemJson。
@@ -949,14 +951,18 @@ async function runQuery(jira, { json, limit, rest, status, jql, scope, search, s
949
951
  const filteredJql = applyStatus(jql, status);
950
952
  // 面板高亮用的优先级名次跟搜索并行拿;拿不到就是 null,界面退回按名字判断,不拖慢也不影响这次查询。
951
953
  const ranksPromise = json ? jira.priorityRanks(signal).catch(() => null) : Promise.resolve(null);
954
+ // 活跃迭代与 JQL 无关,也提前发出去、跟翻页并行,不占关键路径。
955
+ // preview(首屏)刻意不查它:首屏只需要能先画出第一页的行,迭代分组等全量那份补。
956
+ const sprintPromise = json && !preview ? fetchActiveSprint(jira, signal) : undefined;
952
957
  const page = await searchIssues(jira, filteredJql, limit, signal);
953
958
  const ranks = await ranksPromise;
954
- // 只有面板(--json)才多打这一次 count:命令行文本输出保持一次请求。
955
- const totals = json ? await workListCounts(jira, filteredJql, page.issues, signal) : undefined;
959
+ // 只有面板(--json)才要 count;命令行文本输出保持一次请求。
960
+ // 翻页已到底时 workListCounts 本地算总数,不再多打两次 count。
961
+ const totals = json && !preview ? await workListCounts(jira, filteredJql, page.issues, signal, !page.hasMore) : undefined;
956
962
  // 文本输出刻意不再标注「活跃迭代」(用户 2026-11-18:这个 board 的 sprint 状态跟实际工作安排对不上,
957
963
  // 标出来会误导);结构化输出里仍然保留这个字段,供界面或脚本自行取用。
958
964
  return json
959
- ? JSON.stringify(buildWorkListJson(page.issues, filteredJql, scope, jira, await fetchActiveSprint(jira, signal), { limit, hasMore: page.hasMore, status, ranks, search }, totals), null, 2)
965
+ ? JSON.stringify(buildWorkListJson(page.issues, filteredJql, scope, jira, await sprintPromise, { limit, hasMore: page.hasMore, status, ranks, search }, totals, preview), null, 2)
960
966
  : renderWorkList(page.issues, filteredJql, scope, jira, page.hasMore ? page.limit : 0);
961
967
  }
962
968
 
@@ -1361,9 +1367,21 @@ function withProjectClause(jql, name) {
1361
1367
  }
1362
1368
 
1363
1369
  // 面板要的两个数字:当前查询的总数、以及每个项目的总数(项目太多时只给总数)。
1364
- async function workListCounts(jira, jql, issues, signal) {
1365
- const total = await countIssues(jira, jql, signal);
1370
+ // 翻页已经拉到底(complete = !hasMore)时,items 就是全集:两个数字都能本地算出来,
1371
+ // 不再打 approximate-count —— 面板每次打开都重拉,两次 count 是白送的 RTT
1372
+ // (实测一次 count ~0.8s;面板固定 --limit=0,正常情况下每次都能拉完)。
1373
+ async function workListCounts(jira, jql, issues, signal, complete = false) {
1366
1374
  const names = projectNamesOf(issues);
1375
+ if (complete) {
1376
+ const projectTotals = {};
1377
+ for (const issue of issues) {
1378
+ const name = String(issue?.key ?? '').split('-')[0];
1379
+ if (!name) continue;
1380
+ projectTotals[name] = (projectTotals[name] ?? 0) + 1;
1381
+ }
1382
+ return { total: issues.length, projectTotals };
1383
+ }
1384
+ const total = await countIssues(jira, jql, signal);
1367
1385
  if (names.length === 0 || names.length > MAX_COUNT_PROJECTS) return { total };
1368
1386
  const values = await Promise.all(names.map((name) => countIssues(jira, withProjectClause(jql, name), signal)));
1369
1387
  const projectTotals = {};
@@ -3871,7 +3889,7 @@ function countByStatus(issues) {
3871
3889
  * client 面板的载荷:同一次查询换成界面能直接排版的字段,避免在浏览器里解 Markdown。
3872
3890
  * `ok: false` 只在查询本身失败时出现(命令面的 handler 失败会走 kind:'error')。
3873
3891
  */
3874
- function buildWorkListJson(issues, jql, scope, jira, sprint, page, totals) {
3892
+ function buildWorkListJson(issues, jql, scope, jira, sprint, page, totals, preview = false) {
3875
3893
  const counts = { new: 0, indeterminate: 0, done: 0 };
3876
3894
  const ranks = page?.ranks ?? null;
3877
3895
  const items = issues.map((issue) => {
@@ -3894,7 +3912,10 @@ function buildWorkListJson(issues, jql, scope, jira, sprint, page, totals) {
3894
3912
  }, new Map())].map(([name, count]) => ({ name, count })).sort((a, b) => (b.count - a.count) || a.name.localeCompare(b.name)),
3895
3913
  // 界面据此显示「加载更多」:limit 是这次生效的条数上限,hasMore 说明后面还有。
3896
3914
  limit: page?.limit ?? limitOf(jira.settings),
3897
- hasMore: page?.hasMore === true,
3915
+ // 首屏(preview)这一份只是第一页:后面一定还有,界面据此继续显示「加载更多」。
3916
+ hasMore: preview ? true : page?.hasMore === true,
3917
+ // 首屏不查总数:total/projectTotals 留 null,界面等全量那份再显示数字。
3918
+ preview,
3898
3919
  // 准确总数(approximate-count,实测与翻页拉全集一致);拿不到就是 null,面板不显示数字。
3899
3920
  total: Number.isFinite(totals?.total) ? totals.total : null,
3900
3921
  // 每个项目的准确总数;null 表示这次没算(项目太多或查询失败)。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-jira-work-overview",
3
- "version": "0.16.6",
3
+ "version": "0.16.7",
4
4
  "description": "Show your Jira work items and their workflow status inside DeepSeek Harness (DSH) · 在 DSH 里查看我的 Jira 工作项与完成状态",
5
5
  "license": "MIT",
6
6
  "author": "Zhaohong Fei",
package/test/README.md CHANGED
@@ -48,6 +48,7 @@ skip without `JIRA_*` credentials (no secrets are configured on purpose — this
48
48
  | --- | --- | --- |
49
49
  | `dsh-jira-bundle-id.mjs` | no | package identity: `__ModuleLoader__.load({ id })` === `package.json.name` === `cordis.patch.yml insert[].name`, no `@local/` leftovers, client half still a `{ id, factory(require) }` bundle that imports no `@deepseek-ai/*` |
50
50
  | `dsh-jira-visual.mjs` | no | rendering: grouping, collapse, project tabs, status filter, header total, priority highlight, **virtualization** (windowed DOM vs. placeholder height), **in-place status change** (no `/jira` re-fetch, local row + counts), fallback when `@tanstack/react-virtual` is missing |
51
+ | `dsh-jira-resume.mjs` | no | **reopen / resume freshness**: opening the panel after 2 minutes re-fetches the list (a task added meanwhile shows up), reopening while the payload is still new does not, `visibilitychange` → visible re-fetches only when the payload is stale, and a watch change from 0 → 1 unread refreshes the list (the old `before > 0` gate stayed stale after "mark read") |
51
52
  | `dsh-jira-selfwatch.mjs` | no | the watch loop's diff: someone else's status change notifies, a change **you** made (panel POST or `jira_transition`) is swallowed and its baseline advanced, a colleague changing it right afterwards still notifies, a failed write leaves no stale expectation |
52
53
  | `dsh-jira-plan.mjs` | no | the per-row **「计划」 button** end to end: a planning session is created in the project's linked workspace (or in DSH's default Workspace when the project is not linked), `/plan` runs before the first message, that message carries the `JIRA_PLAN_SESSION:<KEY>` token plus the "only report the changes to make" / "stop if the issue is unclear" rules, a second click reuses the same session (local binding, then a token search through the session log), gaps are listed for a thin issue, and a workspace that cannot be resolved at all fails loudly (a missing plan-mode policy does not) |
53
54
  | `dsh-jira-workspace-menu.mjs` | no | the workspace context menu **when `contextMenus` arrives late**: the plugin waits for the service via `ctx.inject` (a single `ctx.get` at apply used to lose the 「关联 Jira 项目…」 entry for the whole page), then registers a `workspace` contribution whose entry opens the panel and reads the link mapping; also covers the older host without `ctx.inject` |
@@ -99,7 +99,8 @@ Object.defineProperty(globalThis, 'fetch', {
99
99
  ]);
100
100
  }
101
101
  if (target.includes('/rest/api/3/search/jql')) {
102
- if (paging.mode === 'natural') return json({ issues: [RECORD], isLast: true });
102
+ // natural = 一页回完 9 条(翻页到底时 total 由本地 items 统计,不走 count)。
103
+ if (paging.mode === 'natural') return json({ issues: pageItems(1, 9), isLast: true });
103
104
  paging.pages += 1;
104
105
  const want = Number(new URL(target).searchParams.get('maxResults')) || 100;
105
106
  const batch = pageItems(paging.pages, Math.min(100, Math.max(1, want)));
@@ -240,7 +241,7 @@ check('--lang 不会跑到 JQL 里(输出里没有 lang 字样残留)', !/--
240
241
  const zhJson = await runCommand('--json --lang=zh');
241
242
  check('--json + --lang 组合可用', zhJson.includes(SUMMARY));
242
243
 
243
- // 面板右侧的「共 N 项」来自 approximate-count(准确总数,不是页内条数)。
244
+ // 面板右侧的「共 N 项」:翻页到底时由本地 items 统计(准确总数,不是 count 端点)。
244
245
  check('载荷里有准确总数 total', zhJsonData.total === 9, String(zhJsonData.total));
245
246
  check('载荷里有每个项目的准确总数 projectTotals', JSON.stringify(zhJsonData.projectTotals) === '{"APP":9}', JSON.stringify(zhJsonData.projectTotals));
246
247
  /* ---- 3b. 状态筛选 --status=:不改 Jira 数据保真,载荷里带 status / statusOptions ---- */
@@ -0,0 +1,401 @@
1
+ /**
2
+ * 离线套件:面板「重新打开 / 从挂起恢复」时列表必须重拉。
3
+ *
4
+ * 用户报的现象(2026-11-30):Mac 合盖一晚上、或把窗口藏起来很久再打开,面板里的任务
5
+ * 列表始终是睡前那一份,只能手动点「刷新」;但新任务的推送、未读角标都正常(watch 长轮询
6
+ * 还活着)。根因是列表只在「首次打开 / 显式操作 / watch 发现变化」时重拉,而 watch 的
7
+ * 自动刷新还要求「之前已经有未读」(before > 0),清过角标后的第一条不会刷新列表。
8
+ *
9
+ * 这个套件用迷你 React + 假 transport 渲染真的 Entry / Panel,验证:
10
+ * A. 首次打开(没有数据)照常拉;
11
+ * B. 关闭 2 分钟后再打开 → 重拉,新任务出现在列表里;
12
+ * C. 关掉 5 秒后再打开(载荷还新)→ 不重拉;
13
+ * D. 窗口恢复可见(visibilitychange)且载荷旧了 → 重拉;载荷还新 → 不重拉;
14
+ * E. 面板开着、watch 从 0 条未读变成 1 条 → 重拉(before > 0 的旧门槛已去掉)。
15
+ *
16
+ * 用法:ELECTRON_RUN_AS_NODE=1 "$BIN" test/dsh-jira-resume.mjs
17
+ */
18
+
19
+ import { fileURLToPath, pathToFileURL } from 'node:url';
20
+ import { dirname } from 'node:path';
21
+
22
+ const WS = dirname(dirname(fileURLToPath(import.meta.url)));
23
+
24
+ /* ----------------------------------------------------------- 迷你 React */
25
+
26
+ const hookStore = new Map();
27
+ let currentComponent = '';
28
+ let hookIndex = 0;
29
+
30
+ function flatten(list) {
31
+ return list.flat(Infinity).filter((item) => item !== null && item !== undefined && item !== false && item !== true);
32
+ }
33
+
34
+ function createElement(type, props, ...children) {
35
+ return { type, props: props ?? {}, children: flatten(children) };
36
+ }
37
+
38
+ function slot(index) {
39
+ let list = hookStore.get(currentComponent);
40
+ if (!list) {
41
+ list = [];
42
+ hookStore.set(currentComponent, list);
43
+ }
44
+ while (list.length <= index) list.push({});
45
+ return list[index];
46
+ }
47
+
48
+ const React = {
49
+ createElement,
50
+ useState(initial) {
51
+ const cell = slot(hookIndex++);
52
+ if (cell.value === undefined) cell.value = typeof initial === 'function' ? initial() : initial;
53
+ return [cell.value, (next) => { cell.value = typeof next === 'function' ? next(cell.value) : next; }];
54
+ },
55
+ useEffect(fn, deps) {
56
+ const cell = slot(hookIndex++);
57
+ const changed = cell.deps === undefined || !deps
58
+ || deps.length !== cell.deps.length || deps.some((dep, i) => dep !== cell.deps[i]);
59
+ if (!changed) return;
60
+ cell.deps = deps;
61
+ cell.cleanup?.();
62
+ cell.cleanup = fn() ?? undefined;
63
+ },
64
+ useRef(initial) {
65
+ const cell = slot(hookIndex++);
66
+ if (cell.value === undefined) cell.value = { current: initial ?? null };
67
+ return cell.value;
68
+ },
69
+ };
70
+
71
+ function expand(element) {
72
+ if (element === null || element === undefined || typeof element === 'boolean') return null;
73
+ if (typeof element === 'string' || typeof element === 'number') return { type: '#text', props: {}, children: [], text: String(element) };
74
+ if (typeof element.type === 'function') {
75
+ const previous = currentComponent;
76
+ const previousIndex = hookIndex;
77
+ currentComponent = element.type.name || 'anonymous';
78
+ hookIndex = 0;
79
+ const rendered = element.type(element.props);
80
+ currentComponent = previous;
81
+ hookIndex = previousIndex;
82
+ return expand(rendered);
83
+ }
84
+ return { ...element, children: flatten(element.children).map(expand).filter(Boolean) };
85
+ }
86
+
87
+ function collect(node, predicate) {
88
+ const hits = [];
89
+ const walk = (row) => {
90
+ if (!row) return;
91
+ if (row.type !== '#text' && predicate(row)) hits.push(row);
92
+ for (const child of row.children ?? []) walk(child);
93
+ };
94
+ walk(node);
95
+ return hits;
96
+ }
97
+
98
+ const virtualizerStub = (options) => {
99
+ const count = Math.max(0, Number(options?.count) || 0);
100
+ const size = 32;
101
+ return {
102
+ getTotalSize: () => count * size,
103
+ getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ index, key: index, start: index * size, size })),
104
+ measureElement: () => undefined,
105
+ scrollToIndex: () => undefined,
106
+ };
107
+ };
108
+
109
+ /* ------------------------------------------------------------- 假 DOM */
110
+
111
+ const styleTags = [];
112
+ const visibilityHandlers = [];
113
+ const documentStub = {
114
+ visibilityState: 'visible',
115
+ head: { appendChild: (tag) => styleTags.push(tag) },
116
+ body: {},
117
+ activeElement: undefined,
118
+ createElement: (tag) => ({
119
+ tagName: tag, dataset: {}, style: {}, textContent: '',
120
+ remove() { this.removed = true; },
121
+ }),
122
+ querySelector: (selector) => styleTags.find((tag) => selector.includes(tag.dataset.pluginCss)) ?? null,
123
+ addEventListener(type, handler) {
124
+ if (type === 'visibilitychange') visibilityHandlers.push(handler);
125
+ },
126
+ removeEventListener(type, handler) {
127
+ if (type !== 'visibilitychange') return;
128
+ const at = visibilityHandlers.indexOf(handler);
129
+ if (at >= 0) visibilityHandlers.splice(at, 1);
130
+ },
131
+ };
132
+ Object.defineProperty(globalThis, 'document', { value: documentStub, configurable: true });
133
+ Object.defineProperty(globalThis, 'navigator', { value: { language: 'zh-CN' }, configurable: true });
134
+
135
+ /* --------------------------------------------------- 假 transport / 数据 */
136
+
137
+ const watchState = { total: 0 };
138
+ const json = (payload, status = 200) => ({
139
+ ok: status < 400,
140
+ status,
141
+ async json() { return payload; },
142
+ async text() { return JSON.stringify(payload); },
143
+ });
144
+
145
+ const item = (key, status = 'Backlog', category = 'new') => ({
146
+ key,
147
+ project: 'APP',
148
+ summary: `${key} summary`,
149
+ status,
150
+ category,
151
+ type: 'Task',
152
+ priority: 'High',
153
+ priorityId: '2',
154
+ priorityRank: 1,
155
+ parent: '',
156
+ parentKey: '',
157
+ parentSummary: '',
158
+ epicKey: '',
159
+ epicSummary: '',
160
+ due: '',
161
+ overdue: false,
162
+ updated: '2026-11-30',
163
+ labels: [],
164
+ sprintId: 30,
165
+ sprint: 'Sprint 30',
166
+ sprintState: 'active',
167
+ sprintStart: '2026-11-01',
168
+ sprintEnd: '2026-11-30',
169
+ url: `https://example.atlassian.net/browse/${key}`,
170
+ });
171
+
172
+ const listPayload = (items) => ({
173
+ ok: true,
174
+ source: 'dsh-jira-work-overview',
175
+ generatedAt: new Date().toISOString(),
176
+ query: { scope: 'all', jql: '', search: '' },
177
+ project: 'APP',
178
+ projects: [{ name: 'APP', count: items.length }],
179
+ limit: 0,
180
+ hasMore: false,
181
+ total: items.length,
182
+ projectTotals: { APP: items.length },
183
+ status: '',
184
+ statusOptions: [...new Set(items.map((row) => row.status))],
185
+ credentialSource: 'config',
186
+ notes: [],
187
+ sprint: null,
188
+ watch: null,
189
+ counts: { new: items.length, indeterminate: 0, done: 0, total: items.length },
190
+ sprints: items.length
191
+ ? [{
192
+ id: 30,
193
+ name: 'Sprint 30',
194
+ state: 'active',
195
+ start: '2026-11-01',
196
+ end: '2026-11-30',
197
+ active: true,
198
+ keys: items.map((row) => row.key),
199
+ counts: { new: items.length, indeterminate: 0, done: 0, total: items.length },
200
+ }]
201
+ : [],
202
+ epics: [],
203
+ items,
204
+ });
205
+
206
+ let fixtureItems = [item('APP-1')];
207
+
208
+ const loaded = [];
209
+ Object.defineProperty(globalThis, 'window', {
210
+ value: {
211
+ __ModuleLoader__: { load(spec) { loaded.push(spec); } },
212
+ __DSH_TRANSPORT__: {
213
+ async fetch(url, init) {
214
+ const path = String(url).split('?')[0];
215
+ const method = String(init?.method ?? 'GET').toUpperCase();
216
+ if (path === '/api/jira-work-overview/state') {
217
+ if (method === 'POST') {
218
+ watchState.total = 0;
219
+ return json({ ok: true, cleared: 1, watch: { counts: { new: 0, status: 0, closed: 0, total: 0 }, changes: [] } });
220
+ }
221
+ // 真宿主是长轮询(最长 25s),stub 也停一下,否则循环会把宏任务饿死。
222
+ await new Promise((resolve) => setTimeout(resolve, 20));
223
+ return json({
224
+ ok: true,
225
+ watch: {
226
+ enabled: true,
227
+ counts: { new: watchState.total, status: 0, closed: 0, total: watchState.total },
228
+ changes: watchState.total ? [{ kind: 'new', key: 'APP-2', summary: 'APP-2 summary', status: 'Backlog' }] : [],
229
+ },
230
+ now: new Date().toISOString(),
231
+ });
232
+ }
233
+ if (path === '/api/jira-work-overview/project-workspace') return json({ ok: true, mapping: {}, workspaces: {} });
234
+ if (path === '/api/jira-work-overview/plan') return json({ ok: true, sessions: {} });
235
+ return json({ ok: true });
236
+ },
237
+ },
238
+ addEventListener() { /* focus / pageshow:这个套件只驱动 visibilitychange */ },
239
+ removeEventListener() { /* 同上 */ },
240
+ },
241
+ configurable: true,
242
+ });
243
+
244
+ /* ------------------------------------------------------------- 迷你宿主 */
245
+
246
+ const calls = [];
247
+ const completed = [];
248
+ const sessionRows = { s1: { id: 's1', retainedBy: { mainView: 1 } } };
249
+ const slotRegistrations = [];
250
+ const effects = [];
251
+
252
+ const clientCtx = {
253
+ get(name) {
254
+ if (name === 'sessions') return { list: { getSnapshot: () => ({ byId: sessionRows }) } };
255
+ if (name === 'remote.commands') {
256
+ return {
257
+ async execute(sessionId, line) {
258
+ calls.push({ sessionId, line });
259
+ completed.push(line);
260
+ // 首屏(--preview)只回第一页:hasMore=true、total=null,跟 host 的口径一致。
261
+ const payload = line.includes('--preview')
262
+ ? { ...listPayload(fixtureItems), items: listPayload(fixtureItems).items.slice(0, 1), hasMore: true, total: null, preview: true }
263
+ : listPayload(fixtureItems);
264
+ return {
265
+ ok: true,
266
+ value: {
267
+ commandId: 'jira',
268
+ result: { kind: 'success', text: JSON.stringify(payload) },
269
+ },
270
+ };
271
+ },
272
+ };
273
+ }
274
+ return undefined;
275
+ },
276
+ effect(fn) {
277
+ const off = fn();
278
+ effects.push(off);
279
+ return () => {};
280
+ },
281
+ slots: {
282
+ inject(name, factory) { factory(); },
283
+ register(options, component) { slotRegistrations.push({ options, component }); return () => {}; },
284
+ },
285
+ };
286
+
287
+ await import(pathToFileURL(`${WS}/client.js`).href);
288
+ const spec = loaded[0];
289
+ if (!spec) throw new Error('client.js 没有调用 window.__ModuleLoader__.load');
290
+ const mod = spec.factory((name) => {
291
+ if (name === 'react') return React;
292
+ if (name === 'react-dom') return { createPortal: (node) => node };
293
+ if (name === '@tanstack/react-virtual') return { useVirtualizer: virtualizerStub };
294
+ return undefined;
295
+ });
296
+ mod.apply(clientCtx);
297
+
298
+ const entryComponent = slotRegistrations.find((row) => row.options.name === 'sidebar.footer.action').component;
299
+ const panelComponent = slotRegistrations.find((row) => row.options.name === 'shell.overlay').component;
300
+
301
+ let failed = 0;
302
+ const check = (ok, label, detail) => {
303
+ console.log(`${ok ? 'PASS' : 'FAIL'} ${label}${detail === undefined ? '' : ` | ${detail}`}`);
304
+ if (!ok) failed += 1;
305
+ };
306
+
307
+ function renderEntry() {
308
+ currentComponent = 'Entry';
309
+ hookIndex = 0;
310
+ return expand(createElement(entryComponent, { wide: true }));
311
+ }
312
+
313
+ function renderPanel() {
314
+ currentComponent = 'Panel';
315
+ hookIndex = 0;
316
+ return expand(createElement(panelComponent, {}));
317
+ }
318
+
319
+ const entryButton = () => collect(renderEntry(), (row) => row.type === 'button')[0];
320
+ const panelRows = () => collect(renderPanel(), (row) => String(row.props.className ?? '').split(' ')[0] === 'jmw-row');
321
+ const toggle = async () => {
322
+ entryButton().props.onClick();
323
+ await settle();
324
+ };
325
+
326
+ const tick = () => new Promise((resolve) => setTimeout(resolve, 0));
327
+ // 两阶段加载:首屏(--preview)之后还有一次全量,所以要等到「没有新命令、且都已返回」才算 settle。
328
+ async function settle() {
329
+ let quiet = 0;
330
+ for (let i = 0; i < 400; i += 1) {
331
+ await new Promise((resolve) => setTimeout(resolve, 20));
332
+ if (calls.length > 0 && completed.length === calls.length) {
333
+ quiet += 1;
334
+ if (quiet >= 2) return;
335
+ } else {
336
+ quiet = 0;
337
+ }
338
+ }
339
+ }
340
+
341
+ // 只数「全量」那一次:首屏是同一份数据的加速版,不算一次独立拉取。
342
+ const loadCalls = () => calls.filter((row) => !row.line.includes('--preview'));
343
+
344
+ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
345
+
346
+ /* ------------------------------------------------ 假时钟(只挪 Date.now) */
347
+
348
+ const realNow = Date.now.bind(Date);
349
+ let clockOffset = 0;
350
+ Date.now = () => realNow() + clockOffset;
351
+
352
+ /* ------------------------------------------------------------- 断言 */
353
+
354
+ await wait(60); // watch 循环首轮建基线
355
+
356
+ // A. 首次打开(没有数据)→ 拉一次。
357
+ await toggle();
358
+ check(loadCalls().length === 1, 'A 首次打开、没有数据 → 拉取列表', `calls=${loadCalls().length}`);
359
+ check(String(calls[0]?.line ?? '').includes('--preview') && String(calls[0]?.line ?? '').includes('--limit=100'),
360
+ 'A 首屏先发 --preview --limit=100(1 页先画)', calls[0]?.line);
361
+ check(panelRows().length === 1, 'A 列表渲染出 1 行', `rows=${panelRows().length}`);
362
+
363
+ // B. 关闭 2 分钟、期间多了一条任务 → 重新打开必须重拉,并看到新任务。
364
+ await toggle(); // 关闭
365
+ check(loadCalls().length === 1, 'B 关闭面板本身不查询', `calls=${loadCalls().length}`);
366
+ fixtureItems = [...fixtureItems, item('APP-2')];
367
+ clockOffset += 2 * 60 * 1000;
368
+ await toggle(); // 打开
369
+ check(loadCalls().length === 2, 'B 关闭 2 分钟后再打开 → 重拉列表', `calls=${loadCalls().length}`);
370
+ check(panelRows().length === 2, 'B 重开后新任务出现在列表里', `rows=${panelRows().length}`);
371
+
372
+ // C. 关掉几秒再打开(载荷还新)→ 不重复查询。
373
+ await toggle(); // 关闭
374
+ clockOffset += 5 * 1000;
375
+ await toggle(); // 打开
376
+ check(loadCalls().length === 2, 'C 载荷还新时重开不重复查询', `calls=${loadCalls().length}`);
377
+
378
+ // D. 窗口恢复可见:载荷旧了 → 重拉;还新 → 不重拉。
379
+ const fireVisibility = async () => {
380
+ documentStub.visibilityState = 'visible';
381
+ for (const handler of [...visibilityHandlers]) handler();
382
+ await wait(200); // 合并窗口
383
+ await settle();
384
+ };
385
+ await fireVisibility();
386
+ check(loadCalls().length === 2, 'D 载荷还新时恢复可见不重拉', `calls=${loadCalls().length}`);
387
+ clockOffset += 2 * 60 * 1000;
388
+ await fireVisibility();
389
+ check(loadCalls().length === 3, 'D 载荷旧了、恢复可见 → 重拉', `calls=${loadCalls().length}`);
390
+
391
+ // E. 面板开着、watch 从 0 条未读变成 1 条 → 重拉(旧实现要求 before > 0,这里不会刷新)。
392
+ watchState.total = 1;
393
+ await wait(120);
394
+ await settle();
395
+ check(loadCalls().length === 4, 'E 清过角标后的第一条变化也刷新列表', `calls=${loadCalls().length}`);
396
+
397
+ for (const off of effects) { try { off?.(); } catch { /* ignore */ } }
398
+ console.log(failed === 0
399
+ ? '\n=== resume:重新打开 / 从挂起恢复时列表必须重拉 —— 全部通过 ==='
400
+ : `\n=== resume:${failed} 项失败 ===`);
401
+ process.exit(failed === 0 ? 0 : 1);
@@ -60,10 +60,20 @@ const issues = [
60
60
  },
61
61
  },
62
62
  ];
63
+ // 12 条同构数据:只给 --limit=10 的截断用例用(>10 才会走 count 路径)。
64
+ const bigRows = Array.from({ length: 12 }, (_, index) => ({
65
+ ...issues[0],
66
+ key: `APP-5${String(index).padStart(3, '0')}`,
67
+ fields: { ...issues[0].fields },
68
+ }));
63
69
 
64
70
  // 每个搜索请求的 jql 都记下来:断言「面板/命令发的 JQL」而不是只看返回。
65
71
  const searchJqls = [];
66
72
  const countJqls = [];
73
+ // 活跃迭代(agile API)的请求次数:首屏(--preview)不该查它。
74
+ let agileCalls = 0;
75
+ // 翻页桩开关:默认一页回完;big 时给 12 条(配合 --limit=10 覆盖「截断 → 走 count」的路径)。
76
+ const pagingStub = { big: false };
67
77
  const json = (body, status = 200) => ({
68
78
  ok: status < 400,
69
79
  status,
@@ -82,19 +92,25 @@ Object.defineProperty(globalThis, 'fetch', {
82
92
  return json([{ id: '1', name: 'Highest' }, { id: '2', name: 'High' }, { id: '3', name: 'Medium' }]);
83
93
  }
84
94
  if (target.includes('/rest/api/3/search/jql')) {
85
- const jql = new URL(target).searchParams.get('jql') ?? '';
95
+ const url = new URL(target);
96
+ const jql = url.searchParams.get('jql') ?? '';
86
97
  searchJqls.push(jql);
87
- // issue key 直达只回那一条;全文搜索回两条(两个 sprint)。
98
+ // issue key 直达只回那一条;全文搜索回两条(两个 sprint);big 模式给 12 条。
88
99
  const key = /^key\s*=\s*"([^"]+)"$/.exec(jql.trim())?.[1];
89
- const rows = key ? issues.filter((issue) => issue.key === key) : issues;
100
+ const rows = key ? issues.filter((issue) => issue.key === key) : (pagingStub.big ? bigRows : issues);
101
+ // 真实站点一页最多回 maxResults 条,剩下的给 nextPageToken;
102
+ // 一页回完(isLast)时 total/projectTotals 由本地 items 统计,不打 count。
103
+ const want = Number(url.searchParams.get('maxResults')) || 100;
104
+ if (rows.length > want) return json({ issues: rows.slice(0, want), nextPageToken: 'tok-next' });
90
105
  return json({ issues: rows, isLast: true });
91
106
  }
92
107
  if (target.includes('/rest/api/3/search/approximate-count')) {
93
108
  const body = JSON.parse(String(init?.body ?? '{}'));
94
109
  countJqls.push(String(body.jql ?? ''));
95
- return json({ count: 2 });
110
+ return json({ count: pagingStub.big ? bigRows.length : 2 });
96
111
  }
97
112
  if (target.includes('/rest/agile/1.0/board/')) {
113
+ agileCalls += 1;
98
114
  return json({ values: [SPRINT_26] });
99
115
  }
100
116
  return json({});
@@ -193,7 +209,9 @@ check('引号与反斜杠被转义',
193
209
  `jql=${JSON.stringify(payload.query?.jql)}`);
194
210
 
195
211
  // 5. 多词搜索词:`--search=` 一路吃到下一个开关为止,一个词都不丢。
196
- payload = await runJson('--search=網上 APP --status=In Review');
212
+ // 用 12 条 + --limit=10 把翻页截断,count 请求才会真的发生(翻到底时总数改为本地统计,见 case 5b)。
213
+ pagingStub.big = true;
214
+ payload = await runJson('--search=網上 APP --status=In Review --limit=10');
197
215
  check('多词搜索词完整保留', payload.query?.search === '網上 APP', `search=${payload.query?.search}`);
198
216
  check('状态筛选拼在 ORDER BY 之前',
199
217
  payload.query?.jql === 'text ~ "網上 APP" AND status = "In Review" ORDER BY updated DESC',
@@ -202,6 +220,32 @@ check('状态筛选拼在 ORDER BY 之前',
202
220
  check('approximate-count 的 JQL 也没有把 ORDER BY 弄乱',
203
221
  countJqls.at(-1) === 'text ~ "網上 APP" AND status = "In Review" AND project = "APP" ORDER BY updated DESC',
204
222
  `count=${countJqls.at(-1)}`);
223
+ check('翻页被 limit 截断时仍用 count 拿准确总数(不是页内条数)',
224
+ payload.total === 12 && payload.hasMore === true && payload.items?.length === 10,
225
+ `total=${payload.total} hasMore=${payload.hasMore} items=${payload.items?.length}`);
226
+ pagingStub.big = false;
227
+
228
+ // 5b. 翻到底(!hasMore)时不再打 approximate-count:总数与每项目数由 items 本地统计。
229
+ const countsBefore = countJqls.length;
230
+ payload = await runJson('--search=網上 APP --limit=0');
231
+ check('翻到底时 total 来自本地统计(= items 条数)', payload.total === payload.items?.length && payload.total === 2,
232
+ `total=${payload.total} items=${payload.items?.length}`);
233
+ check('翻到底时不发 approximate-count', countJqls.length === countsBefore, `counts=${countJqls.length - countsBefore}`);
234
+
235
+ // 5c. `--preview`(面板首屏):只取第一页、不算总数、不查迭代——先把 100 行画出来。
236
+ pagingStub.big = true;
237
+ const previewCounts = countJqls.length;
238
+ const previewAgile = agileCalls;
239
+ payload = await runJson('all --preview --limit=100');
240
+ check('preview 只回第一页并标 hasMore / preview',
241
+ payload.items?.length === 12 && payload.hasMore === true && payload.preview === true,
242
+ `items=${payload.items?.length} hasMore=${payload.hasMore} preview=${payload.preview}`);
243
+ check('preview 不显示总数(total / projectTotals 为 null)',
244
+ payload.total === null && payload.projectTotals === null,
245
+ `total=${payload.total} projectTotals=${JSON.stringify(payload.projectTotals)}`);
246
+ check('preview 不发 approximate-count', countJqls.length === previewCounts, `counts=${countJqls.length - previewCounts}`);
247
+ check('preview 不查活跃迭代', agileCalls === previewAgile, `agile=${agileCalls - previewAgile}`);
248
+ pagingStub.big = false;
205
249
 
206
250
  // 6. 空搜索回退到原来的范围(不会发 text ~ "");面板发的就是 `all … --search=`。
207
251
  payload = await runJson('all --limit=0 --search=');
@@ -13,7 +13,7 @@ const RELEASE = process.argv.includes('--release');
13
13
 
14
14
  // 真站点套件(status / transition / sprint / smoke*)在没凭据时会自己 SKIP 并 exit 0。
15
15
  const SUITES = [
16
- 'bundle-id', 'release', 'platform', 'visual', 'credential', 'plan', 'workspace-menu', 'i18n',
16
+ 'bundle-id', 'release', 'platform', 'visual', 'resume', 'credential', 'plan', 'workspace-menu', 'i18n',
17
17
  'search', 'epic', 'selfwatch', 'json', 'smoke', 'smoke3', 'due', 'sprint', 'status', 'transition',
18
18
  ];
19
19