dsh-kolors 0.1.0 → 0.3.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.
package/README.en.md ADDED
@@ -0,0 +1,79 @@
1
+ # dsh-kolors
2
+
3
+ A sidebar plugin for DeepSeek Harness: draw pictures with the free `Kwai-Kolors/Kolors` model on SiliconFlow.
4
+
5
+ ![The generate page](docs/screenshot-1.png)
6
+
7
+ [中文说明](README.zh.md)
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ dsh plugin add dsh-kolors
13
+ ```
14
+
15
+ Or add it to a profile's dependencies, or paste the package name into **Plugins → Add plugin** inside DSH. The model is fixed at `Kwai-Kolors/Kolors`; there is no model picker.
16
+
17
+ Once installed, **Kolors Image** appears in the left sidebar. Open the Settings tab first and paste a [SiliconFlow](https://cloud.siliconflow.cn/) API key.
18
+
19
+ ## What it does
20
+
21
+ - **Generate** — prompt, five canvases with a proportion preview, steps, guidance, negative prompt, seed, and a watermark switch; the stage can save, download, delete, or zoom.
22
+ - **History** — filter by 1 / 3 / 7 / 30 days or everything, multi-select and bulk delete, zoom, paging, reuse settings, download, copy path, plus a trash with restore, purge, and empty.
23
+ - **Settings** — a key pool with rotation (one key is fine too), the picture folder (typed or chosen with the native picker), and one-click opening of both folders.
24
+
25
+ An unsaved picture lives only in this page: switching tabs, switching to another sidebar page, and reloading all keep it; closing DSH clears it.
26
+ You do not have to sit and watch a generation — switch away and it finishes in the background, with a dot on the tab when the picture is ready.
27
+
28
+ Allowance: 2 pictures per minute and 400 per day per key, gated locally as well, with counters persisted across restarts.
29
+
30
+ The plugin also registers a `kolors_image` tool so the model can draw inside a conversation, sharing the same allowance and the same save folder.
31
+
32
+ ## Files on this machine
33
+
34
+ | Path | Purpose |
35
+ |---|---|
36
+ | `~/.dsh/secrets/kolors.env` | API keys (mode 600) |
37
+ | `~/.dsh/dsh-kolors.json` | Output folder, last used parameters, key metadata, usage, the picture on the stage |
38
+ | `~/.dsh/kolors-frames/` | The bytes behind the stage picture; the UI never points at it, and it is cleared on restart |
39
+ | `<output folder>/dsh-kolors-image/` | Saved pictures plus `index.json` |
40
+ | `<output folder>/dsh-kolors-image/dsh-kolors-trash/` | The trash plus `index.json`, capped at 2000 pictures; the oldest is deleted along with its file |
41
+
42
+ With no folder configured the plugin uses `~/Pictures` when it exists, and the home directory otherwise.
43
+
44
+ ## Limits
45
+
46
+ - Kolors is free, but the platform requires a non-negative balance; an empty wallet answers 402.
47
+ - An upstream image URL lives for one hour, so the picture is downloaded immediately after generation.
48
+ - Only `1024x1024`, `960x1280`, `768x1024`, `720x1440`, and `720x1280` canvases exist.
49
+ - Inference steps cap at 50 (upstream `code 20015`), prompts at 4000 characters, negative prompts at 2000.
50
+ - An embedded webview swallows `target="_blank"`; use **Download** or **Copy path** instead of a new tab.
51
+
52
+ ## Development
53
+
54
+ ```bash
55
+ git clone https://github.com/kit686/dsh-kolors.git
56
+ cd dsh-kolors
57
+ dsh plugin add ./dsh-kolors # or link: it into a profile
58
+ ```
59
+
60
+ Editing `client.js` takes effect on a page reload; editing `index.js` (the Host half) needs a DSH restart.
61
+
62
+ ## Checks
63
+
64
+ CI runs `npm run check`: four offline suites, 200+ assertions, no network and no dependencies.
65
+
66
+ | Command | What it covers |
67
+ |---|---|
68
+ | `npm run check` | Everything offline: syntax + selftest + clientaudit + tabswitch + pathcheck |
69
+ | `node scripts/selftest.mjs` | Host half: key pool, quota windows, save / history / trash / restore / purge, surviving a tab switch, clearing on restart, path escapes, plugin assembly, request body decoding, the trash ceiling, image streaming and 304 |
70
+ | `node scripts/clientaudit.mjs` | Browser half, static: module shape, identifiers, zh/en dictionary parity, theme tokens, hook dependencies, the copy-path branches, background job ownership |
71
+ | `node scripts/tabswitch.mjs` | Runs `client.js` for real: mounts the page, clicks generate, switches away, lands the request, switches back |
72
+ | `node scripts/tabswitch-old.mjs` | Runs the same harness against the previous `client.js`, proving it catches the bug |
73
+ | `node scripts/pathcheck.mjs` | Runs `fullPathOf` against all three row shapes |
74
+ | `node scripts/toolschema.mjs` | Validates the `kolors_image` schema with the real `dsh-tools` (needs a running Harness) |
75
+ | `node scripts/livecheck.mjs` | Hits the running plugin: save, history, trash, restore, purge, image streaming, path escapes (needs a running Harness) |
76
+
77
+ ## License
78
+
79
+ MIT
package/README.md CHANGED
@@ -1,12 +1,30 @@
1
1
  # dsh-kolors
2
2
 
3
- DeepSeek Harness 左侧栏插件:用硅基流动免费的 `Kwai-Kolors/Kolors` 出图。
3
+ [English](README.en.md)
4
+
5
+ DeepSeek Harness 侧栏插件:用硅基流动免费的 `Kwai-Kolors/Kolors` 出图。
6
+
7
+ ![生图页](docs/screenshot-1.png)
8
+
9
+ ## 安装
10
+
11
+ ```bash
12
+ dsh plugin add dsh-kolors
13
+ ```
14
+
15
+ 也可以直接写进 profile 的依赖,或在 DSH 的 **Plugins → Add plugin** 里粘贴包名。模型固定为 `Kwai-Kolors/Kolors`,没有模型选择项。
16
+
17
+ 装好后左侧栏会出现「Kolors生图」,第一次打开先到**设置页**粘一个[硅基流动](https://cloud.siliconflow.cn/)的 API Key。
18
+
19
+ ## 功能
4
20
 
5
21
  - **生图页**:提示词、可调参数(5 档尺寸带比例示意、步数、贴合度、反向提示词、种子、水印开关)、浏览窗口(保存 / 下载 / 删除 / 放大)。
6
22
  - **历史页**:1 / 3 / 7 / 30 天 / 全部筛选,多选与批量删除,放大、翻页、复用参数、下载、复制路径,外加回收站(恢复 / 彻底删除 / 清空)。
7
23
  - **设置页**:Key 池(多 Key 轮换,单 Key 也能用)、图片保存目录(手填或系统选择器)、两个目录的一键打开。
8
24
 
9
- 没保存的图只活在这一页:切标签、刷新页面都还在,彻底关掉 DSH 后清空。
25
+ 没保存的图只活在这一页:切标签、切到别的侧栏页面、刷新页面都还在,彻底关掉 DSH 后清空。
26
+ 出图途中切走不用守着——请求在后台跑完,切回来就能看到;标签上会有小圆点提示新图已出好。
27
+
10
28
  额度:每 Key 每分钟 2 张、每天 400 张,本机先挡一道,计数写盘、重启不清零。
11
29
 
12
30
  同时注册 `kolors_image` 工具,让模型在对话里直接出图,走同一套额度和同一个保存文件夹。
@@ -19,21 +37,43 @@ DeepSeek Harness 左侧栏插件:用硅基流动免费的 `Kwai-Kolors/Kolors`
19
37
  | `~/.dsh/dsh-kolors.json` | 输出目录、上次参数、Key 元数据、用量、当前浏览窗口里的那张图 |
20
38
  | `~/.dsh/kolors-frames/` | 浏览窗口那张图的本体,界面从不指路,重启时清空 |
21
39
  | `<输出目录>/dsh-kolors-image/` | 保存的图 + `index.json` |
22
- | `<输出目录>/dsh-kolors-image/dsh-kolors-trash/` | 回收站 + `index.json` |
40
+ | `<输出目录>/dsh-kolors-image/dsh-kolors-trash/` | 回收站 + `index.json`,上限 2000 张,超出时最旧的连文件一起删 |
41
+
42
+ 没设过输出目录时落在 `~/Pictures`(存在的话),否则落在用户主目录。
23
43
 
24
44
  ## 限制
25
45
 
26
46
  - Kolors 免费,但平台要求账户余额 ≥ 0,余额见底返回 402。
27
47
  - 上游图片地址只活 1 小时,所以生成后立刻下载到本机。
28
48
  - 尺寸只有 `1024x1024`、`960x1280`、`768x1024`、`720x1440`、`720x1280`。
49
+ - 推理步数上限 50(上游 `code 20015`),提示词上限 4000 字,反向提示词上限 2000 字。
29
50
  - 内嵌 webview 会拦掉 `target="_blank"`,用「下载这张」或「复制文件路径」代替新标签页。
30
51
 
52
+ ## 开发
53
+
54
+ ```bash
55
+ git clone https://github.com/kit686/dsh-kolors.git
56
+ cd dsh-kolors
57
+ dsh plugin add ./dsh-kolors # 或者用 link: 指向本地目录
58
+ ```
59
+
60
+ 改 `client.js` 刷新页面即可;改 `index.js`(Host 侧)需要重启 DSH。
61
+
31
62
  ## 自检
32
63
 
64
+ CI 会跑 `npm run check`,四套离线测试合起来 200+ 条断言,不需要网络也不需要装依赖。
65
+
33
66
  | 命令 | 作用 |
34
67
  |---|---|
35
- | `node scripts/selftest.mjs` | Host 侧离线:Key 池、额度窗口、保存/历史/回收站/恢复/清空、换页保持、重启清空、越权路径、插件装配 |
36
- | `node scripts/clientaudit.mjs` | 浏览器侧静态:模块形状、标识符、中英字典对齐、主题令牌、hook 依赖、复制路径分支 |
68
+ | `npm run check` | 全部离线检查:语法 + selftest + clientaudit + tabswitch + pathcheck |
69
+ | `node scripts/selftest.mjs` | Host 侧离线:Key 池、额度窗口、保存/历史/回收站/恢复/清空、换页保持、重启清空、越权路径、插件装配、请求体解码、回收站上限、图片流与 304 |
70
+ | `node scripts/clientaudit.mjs` | 浏览器侧静态:模块形状、标识符、中英字典对齐、主题令牌、hook 依赖、复制路径分支、后台任务归属 |
71
+ | `node scripts/tabswitch.mjs` | 真跑 `client.js`:起一个小 React 运行时,装页面、点生成、切走、让请求落地、切回来 |
72
+ | `node scripts/tabswitch-old.mjs` | 把上面那套跑在上一版 `client.js` 上,证明它确实能抓到这个 bug |
37
73
  | `node scripts/pathcheck.mjs` | 真跑 `fullPathOf`:生图页 / 历史页 / 回收站三种记录形状都要拿到绝对路径 |
38
74
  | `node scripts/toolschema.mjs` | 用真实 `dsh-tools` 校验 `kolors_image` 的出入参 schema(需 Harness 在跑) |
39
75
  | `node scripts/livecheck.mjs` | 打到运行中的插件:保存、历史、回收站、恢复、清空、图片流、越权(需 Harness 在跑) |
76
+
77
+ ## License
78
+
79
+ MIT
package/README.zh.md ADDED
@@ -0,0 +1,79 @@
1
+ # dsh-kolors
2
+
3
+ [English](README.en.md)
4
+
5
+ DeepSeek Harness 侧栏插件:用硅基流动免费的 `Kwai-Kolors/Kolors` 出图。
6
+
7
+ ![生图页](docs/screenshot-1.png)
8
+
9
+ ## 安装
10
+
11
+ ```bash
12
+ dsh plugin add dsh-kolors
13
+ ```
14
+
15
+ 也可以直接写进 profile 的依赖,或在 DSH 的 **Plugins → Add plugin** 里粘贴包名。模型固定为 `Kwai-Kolors/Kolors`,没有模型选择项。
16
+
17
+ 装好后左侧栏会出现「Kolors生图」,第一次打开先到**设置页**粘一个[硅基流动](https://cloud.siliconflow.cn/)的 API Key。
18
+
19
+ ## 功能
20
+
21
+ - **生图页**:提示词、可调参数(5 档尺寸带比例示意、步数、贴合度、反向提示词、种子、水印开关)、浏览窗口(保存 / 下载 / 删除 / 放大)。
22
+ - **历史页**:1 / 3 / 7 / 30 天 / 全部筛选,多选与批量删除,放大、翻页、复用参数、下载、复制路径,外加回收站(恢复 / 彻底删除 / 清空)。
23
+ - **设置页**:Key 池(多 Key 轮换,单 Key 也能用)、图片保存目录(手填或系统选择器)、两个目录的一键打开。
24
+
25
+ 没保存的图只活在这一页:切标签、切到别的侧栏页面、刷新页面都还在,彻底关掉 DSH 后清空。
26
+ 出图途中切走不用守着——请求在后台跑完,切回来就能看到;标签上会有小圆点提示新图已出好。
27
+
28
+ 额度:每 Key 每分钟 2 张、每天 400 张,本机先挡一道,计数写盘、重启不清零。
29
+
30
+ 同时注册 `kolors_image` 工具,让模型在对话里直接出图,走同一套额度和同一个保存文件夹。
31
+
32
+ ## 本机文件
33
+
34
+ | 文件 | 用途 |
35
+ |---|---|
36
+ | `~/.dsh/secrets/kolors.env` | API Key(权限 600) |
37
+ | `~/.dsh/dsh-kolors.json` | 输出目录、上次参数、Key 元数据、用量、当前浏览窗口里的那张图 |
38
+ | `~/.dsh/kolors-frames/` | 浏览窗口那张图的本体,界面从不指路,重启时清空 |
39
+ | `<输出目录>/dsh-kolors-image/` | 保存的图 + `index.json` |
40
+ | `<输出目录>/dsh-kolors-image/dsh-kolors-trash/` | 回收站 + `index.json`,上限 2000 张,超出时最旧的连文件一起删 |
41
+
42
+ 没设过输出目录时落在 `~/Pictures`(存在的话),否则落在用户主目录。
43
+
44
+ ## 限制
45
+
46
+ - Kolors 免费,但平台要求账户余额 ≥ 0,余额见底返回 402。
47
+ - 上游图片地址只活 1 小时,所以生成后立刻下载到本机。
48
+ - 尺寸只有 `1024x1024`、`960x1280`、`768x1024`、`720x1440`、`720x1280`。
49
+ - 推理步数上限 50(上游 `code 20015`),提示词上限 4000 字,反向提示词上限 2000 字。
50
+ - 内嵌 webview 会拦掉 `target="_blank"`,用「下载这张」或「复制文件路径」代替新标签页。
51
+
52
+ ## 开发
53
+
54
+ ```bash
55
+ git clone https://github.com/kit686/dsh-kolors.git
56
+ cd dsh-kolors
57
+ dsh plugin add ./dsh-kolors # 或者用 link: 指向本地目录
58
+ ```
59
+
60
+ 改 `client.js` 刷新页面即可;改 `index.js`(Host 侧)需要重启 DSH。
61
+
62
+ ## 自检
63
+
64
+ CI 会跑 `npm run check`,四套离线测试合起来 200+ 条断言,不需要网络也不需要装依赖。
65
+
66
+ | 命令 | 作用 |
67
+ |---|---|
68
+ | `npm run check` | 全部离线检查:语法 + selftest + clientaudit + tabswitch + pathcheck |
69
+ | `node scripts/selftest.mjs` | Host 侧离线:Key 池、额度窗口、保存/历史/回收站/恢复/清空、换页保持、重启清空、越权路径、插件装配、请求体解码、回收站上限、图片流与 304 |
70
+ | `node scripts/clientaudit.mjs` | 浏览器侧静态:模块形状、标识符、中英字典对齐、主题令牌、hook 依赖、复制路径分支、后台任务归属 |
71
+ | `node scripts/tabswitch.mjs` | 真跑 `client.js`:起一个小 React 运行时,装页面、点生成、切走、让请求落地、切回来 |
72
+ | `node scripts/tabswitch-old.mjs` | 把上面那套跑在上一版 `client.js` 上,证明它确实能抓到这个 bug |
73
+ | `node scripts/pathcheck.mjs` | 真跑 `fullPathOf`:生图页 / 历史页 / 回收站三种记录形状都要拿到绝对路径 |
74
+ | `node scripts/toolschema.mjs` | 用真实 `dsh-tools` 校验 `kolors_image` 的出入参 schema(需 Harness 在跑) |
75
+ | `node scripts/livecheck.mjs` | 打到运行中的插件:保存、历史、回收站、恢复、清空、图片流、越权(需 Harness 在跑) |
76
+
77
+ ## License
78
+
79
+ MIT
Binary file
Binary file
package/client.js CHANGED
@@ -34,6 +34,8 @@ window.__ModuleLoader__.load({
34
34
  title: 'Kolors 生图',
35
35
  subtitle: '硅基流动免费模型,每分钟 2 张、每天 400 张',
36
36
  'tab.generate': '生图', 'tab.history': '历史', 'tab.settings': '设置',
37
+ 'tab.unseen': '新图已经出好了,切回生图页看',
38
+ 'browse.detached': '已切到别的页面,出图照常进行,回来就能看到。',
37
39
  'quota.minute': '本分钟剩 {n} 张', 'quota.day': '今日剩 {n} 张',
38
40
  'quota.none': '额度已用完', 'quota.pool': '{k} 个 Key',
39
41
  'state.reading': '读取中…', 'state.offline': '连不上本地服务',
@@ -57,7 +59,7 @@ window.__ModuleLoader__.load({
57
59
  'zoom.pathCopiedTemp': '路径已复制(保存后才会长期保留)',
58
60
  'zoom.pathMissing': '这张还没存成文件', 'zoom.pathFailed': '复制被拦住了',
59
61
  'params.size': '尺寸', 'params.size.hint': 'Kolors 只认这五档,别的一律报错。',
60
- 'params.steps': '推理步数', 'params.steps.hint': '默认 20。步数越高越细,也越慢。',
62
+ 'params.steps': '推理步数', 'params.steps.hint': '默认 20,上限 50。步数越高越细,也越慢。',
61
63
  'params.guidance': '提示词贴合度', 'params.guidance.hint': '默认 7.5。越高越严格照提示词画,越低越放飞。',
62
64
  'params.negative': '反向提示词', 'params.negative.hint': '不想出现的东西写这里,可以不填。',
63
65
  'params.negative.placeholder': '比如:模糊、低清、多余的手指、水印',
@@ -113,6 +115,8 @@ window.__ModuleLoader__.load({
113
115
  title: 'Kolors image desk',
114
116
  subtitle: 'Free SiliconFlow model — 2 a minute, 400 a day',
115
117
  'tab.generate': 'Generate', 'tab.history': 'History', 'tab.settings': 'Settings',
118
+ 'tab.unseen': 'Your picture is ready — switch back to Generate',
119
+ 'browse.detached': 'You moved to another page; the picture keeps cooking and will be here when you come back.',
116
120
  'quota.minute': '{n} left this minute', 'quota.day': '{n} left today',
117
121
  'quota.none': 'Out of allowance', 'quota.pool': '{k} keys',
118
122
  'state.reading': 'Loading…', 'state.offline': 'Local service unreachable',
@@ -136,7 +140,7 @@ window.__ModuleLoader__.load({
136
140
  'zoom.pathCopiedTemp': 'Path copied (kept only after Save)',
137
141
  'zoom.pathMissing': 'Not a file yet', 'zoom.pathFailed': 'Copy was blocked',
138
142
  'params.size': 'Canvas', 'params.size.hint': 'Kolors accepts exactly these five; anything else is rejected.',
139
- 'params.steps': 'Inference steps', 'params.steps.hint': 'Default 20. More steps, finer and slower.',
143
+ 'params.steps': 'Inference steps', 'params.steps.hint': 'Default 20, max 50. More steps, finer and slower.',
140
144
  'params.guidance': 'Prompt adherence', 'params.guidance.hint': 'Default 7.5. Higher sticks closer to the prompt.',
141
145
  'params.negative': 'Negative prompt', 'params.negative.hint': 'What must not appear. Optional.',
142
146
  'params.negative.placeholder': 'e.g. blurry, low quality, extra fingers, watermark',
@@ -430,6 +434,14 @@ window.__ModuleLoader__.load({
430
434
  @keyframes dshk-spin { to { transform: rotate(360deg); } }
431
435
  @media (prefers-reduced-motion: reduce) { .dshk-ring { animation: none; } }
432
436
 
437
+ /* A job that is still running, or a finished frame waiting on a tab the user
438
+ is not looking at: the tab strip has to say so, or the work is invisible. */
439
+ .dshk-ring.mini { width: 11px; height: 11px; border-width: 1.5px; display: inline-block; margin-left: 6px; vertical-align: -1px; }
440
+ .dshk-dot {
441
+ display: inline-block; width: 6px; height: 6px; border-radius: 50%; margin-left: 6px; vertical-align: 1px;
442
+ background: var(--dsw-alias-brand-primary, #0f1115);
443
+ }
444
+
433
445
  .dshk-stagefoot { display: flex; align-items: center; gap: 8px; margin-top: 12px; flex-wrap: wrap; }
434
446
  .dshk-stagefoot .spacer { flex: 1; }
435
447
  .dshk-meta { margin-top: 12px; display: flex; flex-direction: column; gap: 6px; font-size: 12px; color: var(--dsw-alias-label-tertiary, #81858c); font-variant-numeric: tabular-nums; }
@@ -746,27 +758,150 @@ window.__ModuleLoader__.load({
746
758
 
747
759
  /* ------------------------------------------------------------ generate */
748
760
 
761
+ /**
762
+ * The generation job, and the frame it produces, outlive the tab body that
763
+ * started them.
764
+ *
765
+ * Switching to another tab unmounts that body. The request itself is only a
766
+ * promise, so it kept running and the Host kept working — but `setBusy` and
767
+ * `setResult` arriving afterwards landed on an unmounted component and were
768
+ * dropped. The picture was written to disk, the allowance was spent, and the
769
+ * page never learned about either: the spinner vanished, the frame never
770
+ * appeared, and the quota meter stayed stale. That is the "generation gets
771
+ * interrupted when I click elsewhere" bug, and it is a state-ownership bug,
772
+ * not a network one.
773
+ *
774
+ * So the job lives here at module scope, where an unmount cannot reach it:
775
+ * the fetch runs to completion, the record is written to STAGE, and whichever
776
+ * body is mounted next reads the same record. Nothing ever aborts a request
777
+ * in flight; the only thing that stops a generation is the Host.
778
+ */
779
+ const STAGE = {
780
+ busy: false,
781
+ error: null,
782
+ errorStatus: 0,
783
+ // The unsaved frame on the table, or null. Survives a tab switch, a panel
784
+ // switch, and a remount; the Host's own `lastPreview` pointer covers a
785
+ // full reload.
786
+ result: null,
787
+ // The boot id the held frame belongs to. A frame from a previous Host
788
+ // process is a dead file, so a new boot id retires it instead of showing
789
+ // a broken image.
790
+ boot: '',
791
+ // Set when a frame lands while the generate tab is not on screen. The tab
792
+ // label carries a dot so a finished job cannot go unnoticed, and mounting
793
+ // the tab clears it.
794
+ unseen: false,
795
+ // Whether the generate tab is mounted right now; a completion reads this
796
+ // to decide if the frame is news.
797
+ viewing: false,
798
+ // The seed box is a draft that belongs to the job, not to the tab body:
799
+ // a tab switch must not quietly drop a seed the user typed in.
800
+ seed: '',
801
+ // Filled in by the page while it is mounted. A completion that lands after
802
+ // the last unmount updates nothing, and the fresh mount reads the frame
803
+ // back from the Host instead — which is why these are optional.
804
+ hooks: { onQuota: undefined, onDone: undefined },
805
+ listeners: new Set(),
806
+ }
807
+
808
+ /**
809
+ * Write STAGE and repaint whoever is subscribed.
810
+ *
811
+ * `silent` is for a write nobody renders: on unmount the child's cleanup
812
+ * runs while the page above it is being torn down too, and waking a listener
813
+ * that is on its way out buys nothing.
814
+ */
815
+ function stageSet(patch, silent = false) {
816
+ Object.assign(STAGE, patch)
817
+ if (silent) return
818
+ for (const listener of [...STAGE.listeners]) listener()
819
+ }
820
+
821
+ /** Re-render on every change to STAGE; the object identity never changes. */
822
+ function useStage() {
823
+ const [, bump] = React.useState(0)
824
+ React.useEffect(() => {
825
+ const listener = () => bump((count) => count + 1)
826
+ STAGE.listeners.add(listener)
827
+ return () => { STAGE.listeners.delete(listener) }
828
+ }, [])
829
+ return STAGE
830
+ }
831
+
832
+ /**
833
+ * One generation, started here rather than inside the tab body so a tab or
834
+ * panel switch cannot orphan it. Returns immediately; progress is in STAGE.
835
+ */
836
+ async function runGenerate(request) {
837
+ if (STAGE.busy) return
838
+ const previous = STAGE.result
839
+ stageSet({ busy: true, error: null, errorStatus: 0 })
840
+ try {
841
+ const seedText = String(request.seed ?? '').trim()
842
+ const body = await post('/generate', {
843
+ prompt: request.prompt,
844
+ size: request.params.size,
845
+ steps: request.params.steps,
846
+ guidance: request.params.guidance,
847
+ negative_prompt: request.params.negative,
848
+ seed: seedText === '' ? undefined : Number(seedText),
849
+ watermark: request.params.watermark,
850
+ })
851
+ // The old frame is dropped only after the new one landed, so a slow
852
+ // failure never costs the picture the user was already looking at. A
853
+ // filed frame is not thrown away: it already lives in the save folder
854
+ // and belongs to the history page now.
855
+ if (previous !== null && previous.filed !== true) {
856
+ post('/discard', { file: previous.file }).catch(() => {})
857
+ }
858
+ stageSet({
859
+ result: body.record,
860
+ boot: typeof body.record?.boot === 'string' ? body.record.boot : STAGE.boot,
861
+ // The frame is news only if nobody was looking at the stage when it
862
+ // landed; the tab that is on screen marks it seen on mount.
863
+ unseen: STAGE.viewing !== true,
864
+ })
865
+ if (body.quota !== undefined && STAGE.hooks.onQuota !== undefined) STAGE.hooks.onQuota(body.quota)
866
+ post('/settings', { params: request.params }).catch(() => {})
867
+ if (STAGE.hooks.onDone !== undefined) STAGE.hooks.onDone()
868
+ } catch (failure) {
869
+ stageSet({ error: failure.message, errorStatus: typeof failure.status === 'number' ? failure.status : 0 })
870
+ } finally {
871
+ stageSet({ busy: false })
872
+ }
873
+ }
874
+
749
875
  function GenerateTab({
750
- state, onQuota, onSaved, onGoKey, onDownload, params, setParams, prompt, setPrompt,
751
- seedDraft, result, setResult, onTrashChanged,
876
+ state, onSaved, onGoKey, onDownload, params, setParams, prompt, setPrompt,
877
+ onTrashChanged,
752
878
  }) {
753
- const [busy, setBusy] = React.useState(false)
754
- const [error, setError] = React.useState(null)
755
- const [errorStatus, setErrorStatus] = React.useState(0)
879
+ const stage = useStage()
880
+ const busy = stage.busy
881
+ const result = stage.result
882
+ const error = stage.error
883
+ const errorStatus = stage.errorStatus
756
884
  const [saving, setSaving] = React.useState(false)
757
885
  const [notice, setNotice] = React.useState('')
758
886
  const [zoom, setZoom] = React.useState(null)
759
- const [seedText, setSeedText] = React.useState('')
887
+ // The seed box is not component state: a tab switch unmounts this body,
888
+ // and a seed the user typed in must not come back empty. Same reason the
889
+ // frame and the job live in STAGE.
890
+ const seedText = stage.seed
891
+ const setSeedText = (value) => stageSet({ seed: value })
760
892
  // "Already filed" is a property of the frame itself, not of this component:
761
893
  // a tab switch remounts this body, and the button must still read 已保存.
762
894
  const saved = result !== null && result.filed === true
763
895
 
764
- // "Reuse settings" on the history tab hands the seed down; adopt it once,
765
- // including when the reused picture had no seed at all.
896
+ /**
897
+ * This body owns the "someone is looking at the stage" flag. It is how a
898
+ * completion knows whether the new frame is news, and it clears the dot
899
+ * the tab shows while the user is elsewhere.
900
+ */
766
901
  React.useEffect(() => {
767
- if (seedDraft === null || seedDraft === undefined) return
768
- setSeedText(String(seedDraft))
769
- }, [seedDraft])
902
+ stageSet({ viewing: true, unseen: false })
903
+ return () => { stageSet({ viewing: false }, true) }
904
+ }, [])
770
905
 
771
906
  const sizes = Array.isArray(state?.sizes) && state.sizes.length > 0 ? state.sizes : SIZE_FALLBACK
772
907
  const dayLeft = state?.quota?.dayLeft
@@ -778,46 +913,19 @@ window.__ModuleLoader__.load({
778
913
  const loaded = state !== null
779
914
  const blocked = loaded && dayLeft <= 0
780
915
 
781
- const generate = async () => {
916
+ // Nothing here awaits the request: the job is in runGenerate, which keeps
917
+ // running after this body is unmounted. All this does is hand it the
918
+ // current draft.
919
+ const generate = () => {
782
920
  if (busy || prompt.trim() === '') return
783
- const previous = result
784
- setBusy(true)
785
- setError(null)
786
- setErrorStatus(0)
787
921
  setNotice('')
788
- try {
789
- const body = await post('/generate', {
790
- prompt,
791
- size: params.size,
792
- steps: params.steps,
793
- guidance: params.guidance,
794
- negative_prompt: params.negative,
795
- seed: seedText.trim() === '' ? undefined : Number(seedText.trim()),
796
- watermark: params.watermark,
797
- })
798
- // The old frame is dropped only after the new one landed, so a slow
799
- // failure never costs the picture the user was already looking at. A
800
- // filed frame is not thrown away: it already lives in the save folder
801
- // and belongs to the history page now.
802
- if (previous !== null && previous.filed !== true) {
803
- post('/discard', { file: previous.file }).catch(() => {})
804
- }
805
- setResult(body.record)
806
- if (body.quota !== undefined) onQuota(body.quota)
807
- post('/settings', { params }).catch(() => {})
808
- } catch (failure) {
809
- setError(failure.message)
810
- setErrorStatus(typeof failure.status === 'number' ? failure.status : 0)
811
- } finally {
812
- setBusy(false)
813
- }
922
+ runGenerate({ prompt, params, seed: seedText })
814
923
  }
815
924
 
816
925
  const save = async () => {
817
926
  if (result === null || saved || saving) return
818
927
  setSaving(true)
819
- setError(null)
820
- setErrorStatus(0)
928
+ stageSet({ error: null, errorStatus: 0 })
821
929
  try {
822
930
  const body = await post('/save', {
823
931
  file: result.file,
@@ -836,19 +944,20 @@ window.__ModuleLoader__.load({
836
944
  // rides on the frame itself, so a tab switch keeps 已保存 visible.
837
945
  const filed = body?.saved
838
946
  if (filed !== undefined && typeof filed.src === 'string') {
839
- setResult({
840
- ...result,
841
- id: filed.id,
842
- src: filed.src,
843
- path: filed.path,
844
- name: filed.name,
845
- filed: true,
947
+ stageSet({
948
+ result: {
949
+ ...result,
950
+ id: filed.id,
951
+ src: filed.src,
952
+ path: filed.path,
953
+ name: filed.name,
954
+ filed: true,
955
+ },
846
956
  })
847
957
  }
848
958
  onSaved()
849
959
  } catch (failure) {
850
- setError(failure.message)
851
- setErrorStatus(typeof failure.status === 'number' ? failure.status : 0)
960
+ stageSet({ error: failure.message, errorStatus: typeof failure.status === 'number' ? failure.status : 0 })
852
961
  } finally {
853
962
  setSaving(false)
854
963
  }
@@ -878,7 +987,7 @@ window.__ModuleLoader__.load({
878
987
  } catch {
879
988
  /* the frame goes away either way */
880
989
  }
881
- setResult(null)
990
+ stageSet({ result: null })
882
991
  onTrashChanged()
883
992
  setNotice(t('delete.done'))
884
993
  window.setTimeout(() => setNotice(''), 2400)
@@ -933,7 +1042,7 @@ window.__ModuleLoader__.load({
933
1042
  h('span', { className: 'r' }, size.id.replace('x', '×'))))),
934
1043
  h('p', { className: 'dshk-note' }, t('params.size.hint')),
935
1044
  h(Slider, {
936
- label: t('params.steps'), value: params.steps, min: 1, max: 100, step: 1,
1045
+ label: t('params.steps'), value: params.steps, min: 1, max: 50, step: 1,
937
1046
  hint: t('params.steps.hint'),
938
1047
  onChange: (steps) => setParams({ ...params, steps }),
939
1048
  }),
@@ -973,18 +1082,18 @@ window.__ModuleLoader__.load({
973
1082
  onClick: generate,
974
1083
  }, busy ? t('generate.running') : result !== null ? t('generate.again') : t('generate')))
975
1084
 
976
- let stage
1085
+ let stageBody
977
1086
  if (busy) {
978
- stage = h('div', { className: 'dshk-spin' },
1087
+ stageBody = h('div', { className: 'dshk-spin' },
979
1088
  h('span', { className: 'dshk-ring' }),
980
1089
  h('span', null, t('browse.busy')))
981
1090
  } else if (result !== null) {
982
- stage = h('button', {
1091
+ stageBody = h('button', {
983
1092
  type: 'button', className: 'dshk-work', style: { display: 'block', width: '100%' },
984
1093
  onClick: () => setZoom(result), title: t('zoom.open'),
985
1094
  }, h('img', { src: result.src, alt: result.prompt, style: { maxHeight: 560, maxWidth: '100%', margin: '0 auto' } }))
986
1095
  } else {
987
- stage = h('div', { className: 'dshk-emptystage' },
1096
+ stageBody = h('div', { className: 'dshk-emptystage' },
988
1097
  h('b', null, t('browse.empty')),
989
1098
  t('browse.empty.body'))
990
1099
  }
@@ -1030,7 +1139,7 @@ window.__ModuleLoader__.load({
1030
1139
  h('div', null,
1031
1140
  h('div', { className: 'dshk-card' },
1032
1141
  h('h2', null, t('section.browse')),
1033
- h('div', { className: 'dshk-stage' }, stage),
1142
+ h('div', { className: 'dshk-stage' }, stageBody),
1034
1143
  foot,
1035
1144
  notice === '' ? null : h('p', { className: 'dshk-note', 'data-tone': 'ok' }, notice),
1036
1145
  errorBox,
@@ -1058,7 +1167,12 @@ window.__ModuleLoader__.load({
1058
1167
  h('button', {
1059
1168
  type: 'button', className: 'dshk-work', onClick: () => onOpen(item), title: item.prompt,
1060
1169
  },
1061
- h('div', { className: 'im' }, h('img', { src: item.src, alt: shortOf(item.prompt, 40) })),
1170
+ h('div', { className: 'im' }, h('img', {
1171
+ // A page can hold 400 full-size PNGs; decoding every one of them up
1172
+ // front is what made opening History slow. `lazy` defers the ones
1173
+ // below the fold, and `async` keeps decoding off the main thread.
1174
+ src: item.src, alt: shortOf(item.prompt, 40), loading: 'lazy', decoding: 'async',
1175
+ })),
1062
1176
  h('div', { className: 'tt' }, shortOf(item.prompt, 18)),
1063
1177
  h('div', { className: 'mm' },
1064
1178
  `${whenOf(item.origin === 'preview' || item.deletedAt !== undefined ? item.deletedAt ?? item.at : item.at)}`
@@ -1574,15 +1688,14 @@ window.__ModuleLoader__.load({
1574
1688
  const [items, setItems] = React.useState([])
1575
1689
  const [historyTotal, setHistoryTotal] = React.useState(undefined)
1576
1690
  const [historyTruncated, setHistoryTruncated] = React.useState(false)
1577
- const [reuseSeed, setReuseSeed] = React.useState(null)
1578
1691
  const [offline, setOffline] = React.useState(false)
1579
1692
  const [days, setDays] = React.useState(null)
1580
1693
  const [windows, setWindows] = React.useState([1, 3, 7, 30, 0])
1581
1694
  const [trashItems, setTrashItems] = React.useState([])
1582
1695
  const [trashTotal, setTrashTotal] = React.useState(0)
1583
- // The unsaved frame lives here, not inside the tab body: switching tabs
1584
- // unmounts that body, and a picture must not disappear with it.
1585
- const [result, setResult] = React.useState(null)
1696
+ // The unsaved frame and the job that produces it live in STAGE, outside
1697
+ // this component tree: switching tabs or panels unmounts bodies, and
1698
+ // neither a running request nor the picture it produces may die with them.
1586
1699
  const [notice, setNotice] = React.useState('')
1587
1700
  const [prompt, setPrompt] = React.useState('')
1588
1701
  const [params, setParamsState] = React.useState({ ...DEFAULT_PARAMS })
@@ -1608,8 +1721,15 @@ window.__ModuleLoader__.load({
1608
1721
  if (next?.limits?.windows !== undefined) setWindows(next.limits.windows)
1609
1722
  setDays((current) => (current === null ? next?.limits?.historyDays ?? 7 : current))
1610
1723
  // The Host is the authority on the unsaved frame: it survives a tab
1611
- // switch and a reload, and a new process simply reports none.
1612
- setResult((current) => (current === null ? next?.preview ?? null : current))
1724
+ // switch and a reload, and a new process simply reports none. A frame
1725
+ // this page already holds is newer than the one on disk — a running
1726
+ // job finishes into STAGE, so it must not be overwritten here.
1727
+ const boot = typeof next?.boot === 'string' ? next.boot : ''
1728
+ if (STAGE.result === null || (STAGE.boot !== '' && STAGE.boot !== boot)) {
1729
+ // A new boot id means the frame in hand names a file the retiring
1730
+ // pass already moved to the trash, so it is replaced, not kept.
1731
+ stageSet({ result: next?.preview ?? null, boot })
1732
+ }
1613
1733
  // Adopt once per page load. The draft is stamped with the boot id it
1614
1734
  // was written under, so "same run, keep typing" and "the app was
1615
1735
  // restarted, start clean" are told apart without a timer.
@@ -1689,6 +1809,22 @@ window.__ModuleLoader__.load({
1689
1809
  if (live === 0) setTab('settings')
1690
1810
  }, [state])
1691
1811
 
1812
+ /**
1813
+ * Let the background job reach this page while it is mounted. The job
1814
+ * outlives the tab body, so the only way its completion can move the
1815
+ * quota meters or refresh the history list is through here — and the
1816
+ * callbacks are optional, because a completion that lands while nobody is
1817
+ * mounted is normal and must not throw.
1818
+ */
1819
+ React.useEffect(() => {
1820
+ STAGE.hooks.onQuota = (next) => setState((current) => (current === null ? current : { ...current, quota: next }))
1821
+ STAGE.hooks.onDone = () => { reloadAll() }
1822
+ return () => {
1823
+ STAGE.hooks.onQuota = undefined
1824
+ STAGE.hooks.onDone = undefined
1825
+ }
1826
+ }, [reloadAll])
1827
+
1692
1828
  const reveal = (path) => {
1693
1829
  if (typeof path !== 'string' || path === '') return
1694
1830
  post('/reveal', { path }).then(() => {
@@ -1740,8 +1876,10 @@ window.__ModuleLoader__.load({
1740
1876
  watermark: item.watermark === true,
1741
1877
  })
1742
1878
  // The seed is what makes a re-run reproducible; without it "reuse"
1743
- // would quietly produce a different picture.
1744
- setReuseSeed(item.seed === null || item.seed === undefined ? '' : String(item.seed))
1879
+ // would quietly produce a different picture. It is written straight into
1880
+ // STAGE — the seed box reads from there — so a later tab switch cannot
1881
+ // hand back a stale value.
1882
+ stageSet({ seed: item.seed === null || item.seed === undefined ? '' : String(item.seed) })
1745
1883
  setTab('generate')
1746
1884
  }
1747
1885
 
@@ -1761,12 +1899,24 @@ window.__ModuleLoader__.load({
1761
1899
  h(Meter, { label: t('quota.day', { n: quota.dayLeft }), low: quota.dayLeft <= 10 }),
1762
1900
  h('span', { className: 'dshk-meter' }, t('quota.pool', { k: keyCount })))))
1763
1901
 
1902
+ // The page also watches STAGE so the tab strip can show that a job is
1903
+ // running — or that a finished frame is waiting on a tab the user is not
1904
+ // looking at. Without this the work happens invisibly.
1905
+ const stage = useStage()
1906
+
1764
1907
  const tabs = h('div', { className: 'dshk-tabs', role: 'tablist' }, ['generate', 'history', 'settings'].map((id) =>
1765
1908
  h('button', {
1766
1909
  key: id, type: 'button', className: 'dshk-tab', role: 'tab',
1767
1910
  'aria-selected': String(tab === id),
1768
1911
  'data-on': String(tab === id), onClick: () => setTab(id),
1769
- }, t(`tab.${id}`))))
1912
+ },
1913
+ t(`tab.${id}`),
1914
+ id === 'generate' && stage.busy
1915
+ ? h('span', { className: 'dshk-ring mini', title: t('browse.detached'), 'aria-label': t('browse.detached') })
1916
+ : null,
1917
+ id === 'generate' && !stage.busy && stage.unseen
1918
+ ? h('span', { className: 'dshk-dot', title: t('tab.unseen'), 'aria-label': t('tab.unseen') })
1919
+ : null)))
1770
1920
 
1771
1921
  let body
1772
1922
  if (tab === 'history') {
@@ -1785,10 +1935,8 @@ window.__ModuleLoader__.load({
1785
1935
  body = h(KeyTab, { state, onRefresh: reloadAll, onReveal: reveal })
1786
1936
  } else {
1787
1937
  body = h(GenerateTab, {
1788
- state, params, setParams, prompt, setPrompt, seedDraft: reuseSeed,
1789
- result, setResult,
1938
+ state, params, setParams, prompt, setPrompt,
1790
1939
  onGoKey: () => setTab('settings'),
1791
- onQuota: (next) => setState((current) => (current === null ? current : { ...current, quota: next })),
1792
1940
  onSaved: () => { reloadAll() },
1793
1941
  onTrashChanged: () => { loadTrash() },
1794
1942
  onDownload: download,
Binary file
package/index.js CHANGED
@@ -20,7 +20,7 @@
20
20
  * @module dsh-kolors
21
21
  */
22
22
 
23
- import { chmodSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
23
+ import { chmodSync, copyFileSync, createReadStream, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
24
24
  import { homedir } from 'node:os'
25
25
  import { basename, dirname, isAbsolute, join, resolve, sep } from 'node:path'
26
26
 
@@ -43,6 +43,9 @@ const DAY_LIMIT = 400
43
43
  /** The history page shows this many days back by default. */
44
44
  const HISTORY_DAYS = 7
45
45
 
46
+ /** How many rows one page of history or trash sends to the browser. */
47
+ const HISTORY_PAGE_SIZE = 400
48
+
46
49
  /** Windows before the history page offers. */
47
50
  const HISTORY_WINDOWS = [1, 3, 7, 30, 0]
48
51
 
@@ -69,6 +72,32 @@ const DEFAULT_PARAMS = {
69
72
  watermark: false,
70
73
  }
71
74
 
75
+ /**
76
+ * Upstream refuses anything above 50 with `code 20015: num_inference_steps:
77
+ * Must be less than or equal to 50`, so the ceiling is enforced here rather
78
+ * than discovered after a wasted round trip. Measured against the live API:
79
+ * 50 answers 200, 51 is rejected.
80
+ */
81
+ export const MAX_STEPS = 50
82
+
83
+ /**
84
+ * How much text one request may carry.
85
+ *
86
+ * Kolors itself takes a short caption, not an essay; these are ceilings that
87
+ * refuse an obviously abusive request before it costs a generation, and they sit
88
+ * far above any prompt a person types on purpose.
89
+ */
90
+ const MAX_PROMPT_CHARS = 4000
91
+ const MAX_NEGATIVE_CHARS = 2000
92
+
93
+ /**
94
+ * Two separate deadlines: rendering and fetching the finished picture. They used
95
+ * to share one 180-second AbortSignal, so a generation that took 170 seconds left
96
+ * the download ten.
97
+ */
98
+ const GENERATE_TIMEOUT_MS = 180_000
99
+ const DOWNLOAD_TIMEOUT_MS = 60_000
100
+
72
101
  /** Error carrying the HTTP status the panel should read. */
73
102
  class PanelError extends Error {
74
103
  constructor(status, message) {
@@ -236,9 +265,22 @@ function maskKey(value) {
236
265
 
237
266
  /* --------------------------------------------------------------- settings */
238
267
 
268
+ /**
269
+ * Where pictures go when the user has not chosen a folder.
270
+ *
271
+ * `~/Pictures` is a Windows and macOS convention; on a bare Linux box it does
272
+ * not exist and creating it is presumptuous. The XDG pictures directory is only
273
+ * used when it really is there, and everything else falls back to the home
274
+ * directory itself, which every platform has.
275
+ */
239
276
  function outputDirOf(settings) {
240
277
  const raw = typeof settings.outputDir === 'string' ? settings.outputDir.trim() : ''
241
- return raw === '' ? join(homedir(), 'Pictures') : raw
278
+ if (raw !== '') return raw
279
+ const pictures = join(homedir(), 'Pictures')
280
+ if (existsSync(pictures)) return pictures
281
+ const xdg = process.env.XDG_PICTURES_DIR
282
+ if (typeof xdg === 'string' && xdg !== '' && existsSync(xdg)) return xdg
283
+ return homedir()
242
284
  }
243
285
 
244
286
  function savedRoot(settings) {
@@ -265,9 +307,19 @@ function readSettings() {
265
307
  parsed = {}
266
308
  }
267
309
  const requestedDays = Number(parsed.historyDays)
310
+ const stored = typeof parsed.params === 'object' && parsed.params !== null ? parsed.params : {}
268
311
  const settings = {
269
312
  outputDir: outputDirOf(parsed),
270
- params: { ...DEFAULT_PARAMS, ...(typeof parsed.params === 'object' && parsed.params !== null ? parsed.params : {}) },
313
+ // Re-clamp on read, not only on write: a config saved by an older build can
314
+ // hold a step count the upstream now refuses, and merging it verbatim would
315
+ // carry that refusal into every later run.
316
+ params: {
317
+ ...DEFAULT_PARAMS,
318
+ ...stored,
319
+ size: sizeOf(String(stored.size ?? DEFAULT_PARAMS.size)).id,
320
+ steps: Math.round(clamp(stored.steps, 1, MAX_STEPS, DEFAULT_PARAMS.steps)),
321
+ guidance: clamp(stored.guidance, 0.1, 20, DEFAULT_PARAMS.guidance),
322
+ },
271
323
  keys: Array.isArray(parsed.keys) ? parsed.keys.filter((key) => key !== null && typeof key === 'object') : [],
272
324
  usage: typeof parsed.usage === 'object' && parsed.usage !== null ? parsed.usage : {},
273
325
  // 0 means "everything", which is a real choice and not a missing value.
@@ -413,9 +465,15 @@ function clamp(value, min, max, fallback) {
413
465
  function requestOf(input) {
414
466
  const prompt = String(input?.prompt ?? '').trim()
415
467
  if (prompt === '') throw new PanelError(400, '提示词不能为空。')
468
+ // The panel and the model tool are two independent callers; neither is
469
+ // trusted to bound its own input. The upstream truncates far below this, and a
470
+ // runaway prompt is the cheapest way to spend a request on a worthless image.
471
+ if (prompt.length > MAX_PROMPT_CHARS) {
472
+ throw new PanelError(400, `提示词太长了(${prompt.length} 字),上限 ${MAX_PROMPT_CHARS} 字。`)
473
+ }
416
474
  const size = sizeOf(String(input?.size ?? ''));
417
- const negative = String(input?.negative_prompt ?? '').trim()
418
- const steps = Math.round(clamp(input?.steps, 1, 100, DEFAULT_PARAMS.steps))
475
+ const negative = String(input?.negative_prompt ?? '').trim().slice(0, MAX_NEGATIVE_CHARS)
476
+ const steps = Math.round(clamp(input?.steps, 1, MAX_STEPS, DEFAULT_PARAMS.steps))
419
477
  const guidance = clamp(input?.guidance, 0.1, 20, DEFAULT_PARAMS.guidance)
420
478
  const seedInput = input?.seed
421
479
  const seed = seedInput === undefined || seedInput === null || String(seedInput).trim() === ''
@@ -493,7 +551,10 @@ async function generate(input, options = {}) {
493
551
  if (request.negative !== '') body.negative_prompt = request.negative
494
552
  if (request.seed !== undefined) body.seed = request.seed
495
553
 
496
- const signal = options.signal ?? AbortSignal.timeout(180_000)
554
+ // The generation gets its own deadline. The download below gets a fresh one:
555
+ // sharing a single 180-second budget meant a slow generation left the download
556
+ // a few seconds to finish an already-paid-for picture, which then "failed".
557
+ const signal = options.signal ?? AbortSignal.timeout(GENERATE_TIMEOUT_MS)
497
558
  let payload
498
559
  try {
499
560
  const response = await fetch(API_URL, {
@@ -522,13 +583,21 @@ async function generate(input, options = {}) {
522
583
  payload = await response.json()
523
584
  } catch (error) {
524
585
  if (error instanceof PanelError) throw error
525
- const later = readSettings()
526
- refundUse(later, picked.key.id, now)
527
- writeSettings(later)
528
- const reason = error?.name === 'TimeoutError' || error?.name === 'AbortError'
529
- ? '请求超时(180 秒),上游没有返回。'
586
+ const timedOut = error?.name === 'TimeoutError' || error?.name === 'AbortError'
587
+ // A timeout does not prove the upstream spent nothing: it may well have
588
+ // rendered the picture and only been slow to answer. Returning the stamp
589
+ // would let the user retry, spend a real upstream slot, and then hit a 429
590
+ // the local meter said was impossible. Only refusals that provably cost
591
+ // nothing are refunded; a timeout keeps its stamp.
592
+ if (!timedOut) {
593
+ const later = readSettings()
594
+ refundUse(later, picked.key.id, now)
595
+ writeSettings(later)
596
+ }
597
+ const reason = timedOut
598
+ ? `请求超时(${GENERATE_TIMEOUT_MS / 1000} 秒),上游没有返回。额度先按已用计,等一分钟再试。`
530
599
  : `连不上硅基流动:${error?.message ?? error}`
531
- throw new PanelError(502, reason)
600
+ throw new PanelError(504, reason)
532
601
  }
533
602
 
534
603
  const imageUrl = payload?.images?.[0]?.url
@@ -540,7 +609,9 @@ async function generate(input, options = {}) {
540
609
  }
541
610
  let bytes
542
611
  try {
543
- bytes = await downloadImage(imageUrl, signal)
612
+ // Its own deadline, and it never inherits the caller's abort: the picture is
613
+ // already generated and paid for, so cancelling now would waste it.
614
+ bytes = await downloadImage(imageUrl, AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS))
544
615
  } catch (error) {
545
616
  throw new PanelError(502, error instanceof PanelError ? error.message : '图片下载失败,重试一次。')
546
617
  }
@@ -757,31 +828,65 @@ function moveToTrash(settings, source, input) {
757
828
  origin: String(input?.origin ?? 'preview'),
758
829
  }
759
830
  rows.push(record)
760
- writeTrash(settings, rows.filter((row) => typeof row.path === 'string' && existsSync(row.path)).slice(-2000))
831
+ writeTrash(settings, pruneTrash(settings, rows))
761
832
  // The caller re-reads settings, so persist the cleared preview pointer here.
762
833
  writeSettings(settings)
763
834
  return record
764
835
  }
765
836
 
837
+ /**
838
+ * The trash ceiling. Once it is reached the oldest entry is evicted, and
839
+ * eviction deletes the file as well as the row.
840
+ *
841
+ * Dropping only the index row used to leave the PNG on disk with nothing that
842
+ * named it: invisible in the panel, unreachable from the UI, and impossible to
843
+ * remove without opening the folder by hand. Every delete past the ceiling
844
+ * leaked one more file.
845
+ */
846
+ const TRASH_LIMIT = 2000
847
+
848
+ function pruneTrash(settings, rows) {
849
+ const alive = []
850
+ for (const row of rows) {
851
+ // A row whose file is gone cannot be restored or previewed.
852
+ if (typeof row.path !== 'string' || !existsSync(row.path)) continue
853
+ alive.push(row)
854
+ }
855
+ alive.sort((a, b) => Number(a.deletedAt ?? a.at ?? 0) - Number(b.deletedAt ?? b.at ?? 0))
856
+ const evicted = alive.length > TRASH_LIMIT ? alive.splice(0, alive.length - TRASH_LIMIT) : []
857
+ for (const row of evicted) {
858
+ try { rmSync(row.path, { force: true }) } catch { /* the row still goes */ }
859
+ }
860
+ return alive
861
+ }
862
+
766
863
  /** The saved pictures inside one time window; 0 days means everything. */
767
864
  function history(days) {
768
865
  const settings = readSettings()
769
866
  const wanted = HISTORY_WINDOWS.includes(Number(days)) ? Number(days) : settings.historyDays
770
867
  const since = wanted === 0 ? 0 : Date.now() - wanted * 86_400_000
771
- const rows = readIndex(settings)
868
+ // Filter by the window first — it is pure arithmetic — then stat only the
869
+ // rows that can still reach the page. Checking every row in the index meant
870
+ // thousands of synchronous statSync calls per history read, on the event loop.
871
+ const inWindow = readIndex(settings)
772
872
  .filter((row) => typeof row.at === 'number' && row.at >= since)
773
- .filter((row) => typeof row.path === 'string' && existsSync(row.path))
774
873
  .sort((a, b) => b.at - a.at)
874
+ const alive = []
875
+ for (const row of inWindow) {
876
+ if (alive.length === HISTORY_PAGE_SIZE) break
877
+ if (typeof row.path !== 'string' || !existsSync(row.path)) continue
878
+ alive.push(row)
879
+ }
775
880
  // The page shows a bounded window; say so instead of silently dropping rows.
776
- const items = rows.slice(0, 400).map((row) => ({ ...row, src: savedUrl(row.path) }))
881
+ const items = alive.map((row) => ({ ...row, src: savedUrl(row.path) }))
777
882
  return {
778
883
  ok: true,
779
884
  days: wanted,
780
885
  windows: HISTORY_WINDOWS,
781
886
  folder: savedRoot(settings),
782
887
  items,
783
- total: rows.length,
784
- truncated: rows.length > items.length,
888
+ total: inWindow.length,
889
+ truncated: inWindow.length > items.length,
785
890
  }
786
891
  }
787
892
 
@@ -807,12 +912,17 @@ function deleteSaved(input) {
807
912
  function trash() {
808
913
  const settings = readSettings()
809
914
  const rows = readTrash(settings)
810
- const alive = rows
811
- .filter((row) => typeof row.path === 'string' && existsSync(row.path))
812
915
  .sort((a, b) => (b.deletedAt ?? 0) - (a.deletedAt ?? 0))
813
- if (alive.length !== rows.length) writeTrash(settings, alive)
814
- const items = alive.slice(0, 400).map((row) => ({ ...row, src: trashUrl(row.path) }))
815
- return { ok: true, folder: trashRoot(settings), items, total: alive.length, truncated: alive.length > items.length }
916
+ // Sort first, then stat only the rows that can reach the page — same reason as
917
+ // in history(): statSync is synchronous and this runs on the event loop.
918
+ const alive = []
919
+ for (const row of rows) {
920
+ if (alive.length === HISTORY_PAGE_SIZE) break
921
+ if (typeof row.path !== 'string' || !existsSync(row.path)) continue
922
+ alive.push(row)
923
+ }
924
+ const items = alive.map((row) => ({ ...row, src: trashUrl(row.path) }))
925
+ return { ok: true, folder: trashRoot(settings), items, total: rows.length, truncated: rows.length > items.length }
816
926
  }
817
927
 
818
928
  /** Put one trashed picture back into the save folder. */
@@ -969,7 +1079,7 @@ function settingsAction(input) {
969
1079
  if (typeof input?.params === 'object' && input.params !== null) {
970
1080
  settings.params = {
971
1081
  size: sizeOf(String(input.params.size ?? settings.params.size)).id,
972
- steps: Math.round(clamp(input.params.steps, 1, 100, settings.params.steps)),
1082
+ steps: Math.round(clamp(input.params.steps, 1, MAX_STEPS, settings.params.steps)),
973
1083
  guidance: clamp(input.params.guidance, 0.1, 20, settings.params.guidance),
974
1084
  negative: String(input.params.negative ?? settings.params.negative ?? '').slice(0, 2000),
975
1085
  watermark: input.params.watermark === true,
@@ -1033,12 +1143,40 @@ function originAllowed(req) {
1033
1143
  }
1034
1144
  }
1035
1145
 
1146
+ /**
1147
+ * The largest RPC body this panel accepts.
1148
+ *
1149
+ * The only bulk field is a prompt or a negative prompt; 1 MiB is far beyond any
1150
+ * useful prompt (roughly 350k Chinese characters) and keeps a runaway caller
1151
+ * from turning the body reader into a memory amplifier.
1152
+ */
1153
+ const MAX_BODY_BYTES = 1024 * 1024
1154
+
1155
+ /**
1156
+ * Read one JSON body.
1157
+ *
1158
+ * The chunks are concatenated as buffers, never decoded one at a time: a TCP
1159
+ * segment boundary lands wherever it likes, and `String(chunk)` on each piece
1160
+ * splits a multi-byte character across two decodes. Each half then becomes
1161
+ * U+FFFD, so a long Chinese prompt silently arrived at the model with mojibake
1162
+ * in it — measured at roughly 22k Chinese characters, where the body first
1163
+ * spans more than one 64 KiB read. Decoding once, after the whole body is in
1164
+ * hand, cannot split a character.
1165
+ */
1036
1166
  async function readBody(req) {
1037
- let raw = ''
1038
- for await (const chunk of req) raw += String(chunk)
1039
- if (raw === '') return {}
1167
+ const chunks = []
1168
+ let total = 0
1169
+ for await (const chunk of req) {
1170
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), 'utf8')
1171
+ total += bytes.length
1172
+ // Refuse rather than buffer without bound; the caller is not a browser the
1173
+ // user is watching, so a silent OOM would be the worst outcome.
1174
+ if (total > MAX_BODY_BYTES) throw new PanelError(413, `请求体超过 ${MAX_BODY_BYTES} 字节。`)
1175
+ chunks.push(bytes)
1176
+ }
1177
+ if (total === 0) return {}
1040
1178
  try {
1041
- const parsed = JSON.parse(raw)
1179
+ const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'))
1042
1180
  return parsed !== null && typeof parsed === 'object' ? parsed : {}
1043
1181
  } catch {
1044
1182
  return {}
@@ -1055,20 +1193,68 @@ function sendJson(res, status, value) {
1055
1193
  res.end(body)
1056
1194
  }
1057
1195
 
1058
- /** Stream one picture, but only from the folder its route owns. */
1059
- function sendFile(res, root, rawPath, mediaType = 'image/png') {
1196
+ /**
1197
+ * Stream one picture, but only from the folder its route owns.
1198
+ *
1199
+ * Two things matter here and neither is decoration:
1200
+ *
1201
+ * - The bytes are piped, not read into a Buffer. The history page can ask for
1202
+ * hundreds of multi-megabyte PNGs at once, and `readFileSync` would hold every
1203
+ * one of them in the Host's heap simultaneously.
1204
+ * - The response carries a validator. The panel re-fetches the same pictures on
1205
+ * every tab switch, and a picture never changes once written, so `ETag` +
1206
+ * `If-None-Match` turns those re-reads into 304s with no body at all.
1207
+ *
1208
+ * `no-store` is deliberately gone: with an ETag the browser may keep its own
1209
+ * copy, and a 304 still revalidates it, so a deleted picture stops being served
1210
+ * rather than being shown from a stale cache forever.
1211
+ */
1212
+ function sendFile(req, res, root, rawPath, mediaType = 'image/png') {
1060
1213
  const target = rawPath === null ? '' : rawPath
1061
1214
  if (target === '' || !insidePath(root, target)) {
1062
1215
  sendJson(res, 403, { ok: false, message: 'path outside the picture folder' })
1063
1216
  return
1064
1217
  }
1065
- let size = 0
1066
- try { size = statSync(target).size } catch {
1218
+ let info
1219
+ try {
1220
+ info = statSync(target)
1221
+ } catch {
1067
1222
  sendJson(res, 404, { ok: false, message: '图片不在了' })
1068
1223
  return
1069
1224
  }
1070
- res.writeHead(200, { 'content-type': mediaType, 'content-length': size, 'cache-control': 'no-store' })
1071
- res.end(readFileSync(target))
1225
+ if (!info.isFile()) {
1226
+ sendJson(res, 404, { ok: false, message: '图片不在了' })
1227
+ return
1228
+ }
1229
+ // Size and mtime identify the bytes: the plugin writes a file once, under a
1230
+ // random name, and never rewrites it.
1231
+ const etag = `"${info.size.toString(16)}-${Math.floor(info.mtimeMs).toString(16)}"`
1232
+ if (req?.headers?.['if-none-match'] === etag) {
1233
+ res.writeHead(304, { etag, 'cache-control': 'private, max-age=0, must-revalidate' })
1234
+ res.end()
1235
+ return
1236
+ }
1237
+ res.writeHead(200, {
1238
+ 'content-type': mediaType,
1239
+ 'content-length': info.size,
1240
+ etag,
1241
+ 'cache-control': 'private, max-age=0, must-revalidate',
1242
+ })
1243
+ if (req === undefined) {
1244
+ // A caller without a request object cannot revalidate, so it gets the bytes.
1245
+ res.end(readFileSync(target))
1246
+ return
1247
+ }
1248
+ const stream = createReadStream(target)
1249
+ stream.on('error', () => {
1250
+ // The headers are already out; the only honest signal left is to cut the
1251
+ // connection so the browser does not treat a short body as the whole file.
1252
+ res.destroy()
1253
+ })
1254
+ // A client that navigates away mid-transfer leaves a half-consumed stream;
1255
+ // close it rather than waiting for the descriptor to be collected.
1256
+ res.on('close', () => { stream.destroy() })
1257
+ stream.pipe(res)
1072
1258
  }
1073
1259
 
1074
1260
  /** The `/kolors` prefix handler: panel RPC plus the picture streams. */
@@ -1096,15 +1282,15 @@ export function createHandler() {
1096
1282
  return
1097
1283
  }
1098
1284
  if (route === '/frame' && method === 'GET') {
1099
- sendFile(res, frameDir(), url.searchParams.get('p'))
1285
+ sendFile(req, res, frameDir(), url.searchParams.get('p'))
1100
1286
  return
1101
1287
  }
1102
1288
  if (route === '/saved' && method === 'GET') {
1103
- sendFile(res, savedRoot(readSettings()), url.searchParams.get('p'))
1289
+ sendFile(req, res, savedRoot(readSettings()), url.searchParams.get('p'))
1104
1290
  return
1105
1291
  }
1106
1292
  if (route === '/trash-file' && method === 'GET') {
1107
- sendFile(res, trashRoot(readSettings()), url.searchParams.get('p'))
1293
+ sendFile(req, res, trashRoot(readSettings()), url.searchParams.get('p'))
1108
1294
  return
1109
1295
  }
1110
1296
  if (method === 'POST') {
@@ -1198,7 +1384,7 @@ function toolDefinition(ctx) {
1198
1384
  enum: SIZES.map((size) => size.id),
1199
1385
  },
1200
1386
  negative_prompt: { type: 'string', description: 'What must not appear in the picture.' },
1201
- steps: { type: 'integer', description: 'Inference steps, 1-100; default 20. Higher is slower and usually finer.' },
1387
+ steps: { type: 'integer', description: 'Inference steps, 1-50; default 20. Higher is slower and usually finer.' },
1202
1388
  guidance: { type: 'number', description: 'Prompt adherence 0.1-20; default 7.5. Higher sticks closer to the prompt.' },
1203
1389
  seed: { type: 'integer', description: 'Random seed; omit for a fresh one. Reuse it to repeat a composition.' },
1204
1390
  watermark: { type: 'boolean', description: 'Draw the explicit "AI generated" watermark; default false (off).' },
package/package.json CHANGED
@@ -1,29 +1,34 @@
1
1
  {
2
2
  "name": "dsh-kolors",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Kolors image desk for DeepSeek Harness: a sidebar page that hard-locks the free Kwai-Kolors/Kolors model on SiliconFlow, keeps a local key pool with per-minute and per-day quotas, saves pictures to a folder you choose, and offers a history with a trash and a model tool.",
5
5
  "type": "module",
6
- "icon": "icon.svg",
6
+ "icon": "assets/icon-512.png",
7
7
  "main": "index.js",
8
8
  "exports": {
9
9
  ".": "./index.js",
10
10
  "./client": "./client.js",
11
11
  "./package.json": "./package.json",
12
12
  "./locale/*.json": "./locale/*.json",
13
- "./icon": "./icon.svg"
13
+ "./icon": "./assets/icon-512.png"
14
14
  },
15
15
  "files": [
16
16
  "index.js",
17
17
  "client.js",
18
18
  "cordis.patch.yml",
19
19
  "locale/*.json",
20
- "docs",
20
+ "docs/preview.svg",
21
+ "docs/screenshot-1.png",
22
+ "assets",
23
+ "screenshots.json",
21
24
  "icon.svg",
22
25
  "README.md",
26
+ "README.en.md",
27
+ "README.zh.md",
23
28
  "LICENSE"
24
29
  ],
25
30
  "scripts": {
26
- "check": "node --check index.js && node --check client.js && node scripts/selftest.mjs && node scripts/clientaudit.mjs && node scripts/pathcheck.mjs",
31
+ "check": "node --check index.js && node --check client.js && node scripts/selftest.mjs && node scripts/clientaudit.mjs && node scripts/tabswitch.mjs && node scripts/pathcheck.mjs",
27
32
  "check:live": "node scripts/livecheck.mjs",
28
33
  "check:tool": "node scripts/toolschema.mjs"
29
34
  },
@@ -0,0 +1,3 @@
1
+ [
2
+ "docs/screenshot-1.png"
3
+ ]
package/docs/DETAIL.md DELETED
@@ -1 +0,0 @@
1
- ![The prompt and its five canvases, two sliders and a switch on the left; the generated picture with its save and delete buttons on the right](preview.svg)
package/docs/DETAIL.zh.md DELETED
@@ -1 +0,0 @@
1
- ![左侧是提示词与五档尺寸、两条滑杆和一个开关,右侧是生成出来的那张图,图下方是保存与删除按钮](preview.svg)