@myrialabs/clopen 0.4.39 → 0.4.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/.env.example +1 -1
  2. package/backend/artifacts/detect.ts +15 -3
  3. package/backend/artifacts/generate.ts +2 -2
  4. package/backend/artifacts/index.ts +12 -4
  5. package/backend/artifacts/markers.ts +24 -1
  6. package/backend/artifacts/matrix.ts +47 -3
  7. package/backend/artifacts/sync.test.ts +3 -3
  8. package/backend/artifacts/sync.ts +8 -20
  9. package/backend/artifacts/types.ts +9 -3
  10. package/backend/auth/permissions.ts +29 -11
  11. package/backend/auth/session-cleanup.ts +10 -1
  12. package/backend/auth/tokens.ts +9 -1
  13. package/backend/chat/stream-manager.ts +42 -0
  14. package/backend/database/crypto/secret-columns.ts +5 -1
  15. package/backend/database/migrations/078_create_worktree_branch_tables.ts +158 -0
  16. package/backend/database/migrations/079_merge_commands_into_skills.ts +222 -0
  17. package/backend/database/migrations/080_create_file_shares.ts +111 -0
  18. package/backend/database/migrations/081_create_push_subscriptions.ts +32 -0
  19. package/backend/database/migrations/index.ts +28 -0
  20. package/backend/database/queries/file-share-queries.ts +163 -0
  21. package/backend/database/queries/index.ts +12 -4
  22. package/backend/database/queries/profile-queries.ts +5 -3
  23. package/backend/database/queries/push-subscription-queries.test.ts +90 -0
  24. package/backend/database/queries/push-subscription-queries.ts +99 -0
  25. package/backend/database/queries/skill-queries.ts +96 -18
  26. package/backend/database/queries/worktree-branch-queries.ts +331 -0
  27. package/backend/db-client/cloning.test.ts +161 -0
  28. package/backend/db-client/cloning.ts +672 -0
  29. package/backend/db-client/connection-url.test.ts +117 -0
  30. package/backend/db-client/connection-url.ts +126 -0
  31. package/backend/db-client/drivers/mongodb.ts +2 -14
  32. package/backend/db-client/drivers/mysql.ts +2 -8
  33. package/backend/db-client/drivers/postgres.ts +10 -13
  34. package/backend/db-client/drivers/redis.ts +2 -6
  35. package/backend/db-client/env/detect.ts +438 -0
  36. package/backend/db-client/env/diff.ts +94 -0
  37. package/backend/db-client/env/env.test.ts +574 -0
  38. package/backend/db-client/env/index.ts +15 -0
  39. package/backend/db-client/env/naming.ts +202 -0
  40. package/backend/db-client/env/service.ts +487 -0
  41. package/backend/db-client/integrations/index.ts +7 -0
  42. package/backend/db-client/integrations/links.ts +41 -10
  43. package/backend/db-client/providers/neon/adapter.ts +522 -0
  44. package/backend/db-client/providers/neon/api-types.ts +182 -0
  45. package/backend/db-client/providers/neon/client.ts +298 -0
  46. package/backend/db-client/providers/neon/endpoints.test.ts +201 -0
  47. package/backend/db-client/providers/neon/endpoints.ts +314 -0
  48. package/backend/db-client/providers/neon/list.test.ts +181 -0
  49. package/backend/db-client/providers/supabase/adapter.ts +25 -2
  50. package/backend/db-client/providers/types.ts +57 -0
  51. package/backend/engine/adapters/claude/stream.ts +2 -1
  52. package/backend/engine/adapters/cline/stream.ts +3 -3
  53. package/backend/engine/adapters/codex/stream.ts +3 -3
  54. package/backend/engine/adapters/copilot/stream.ts +3 -3
  55. package/backend/engine/adapters/cursor/stream.ts +25 -3
  56. package/backend/engine/adapters/opencode/stream.ts +4 -6
  57. package/backend/engine/adapters/pi/stream.ts +2 -2
  58. package/backend/engine/adapters/qwen/stream.ts +2 -2
  59. package/backend/engine/artifact-sync.ts +26 -20
  60. package/backend/engine/docs/artifacts.md +81 -22
  61. package/backend/engine/docs/quick-reference.md +2 -1
  62. package/backend/engine/resolve-model.test.ts +108 -0
  63. package/backend/engine/resolve-model.ts +53 -10
  64. package/backend/engine/structured-helpers.ts +22 -0
  65. package/backend/env-files/discovery.ts +48 -0
  66. package/backend/env-files/edit.ts +213 -0
  67. package/backend/env-files/env-files.test.ts +515 -0
  68. package/backend/env-files/git.ts +27 -0
  69. package/backend/env-files/index.ts +44 -0
  70. package/backend/env-files/keys.ts +69 -0
  71. package/backend/env-files/parse.ts +157 -0
  72. package/backend/env-files/write.ts +229 -0
  73. package/backend/files/file-shares.ts +369 -0
  74. package/backend/files/path-browsing.ts +27 -21
  75. package/backend/http/files-shared.test.ts +505 -0
  76. package/backend/http/files-shared.ts +351 -0
  77. package/backend/http/push.ts +150 -0
  78. package/backend/index.ts +8 -0
  79. package/backend/instructions/index.ts +1 -1
  80. package/backend/instructions/sync.ts +30 -6
  81. package/backend/integrations/health.ts +18 -4
  82. package/backend/integrations/projections/types.ts +9 -2
  83. package/backend/integrations/registry/index.ts +3 -0
  84. package/backend/integrations/registry/providers/context7.ts +1 -0
  85. package/backend/integrations/registry/providers/firecrawl.ts +1 -0
  86. package/backend/integrations/registry/providers/github.ts +1 -0
  87. package/backend/integrations/registry/providers/neon.ts +55 -0
  88. package/backend/integrations/registry/providers/supabase.ts +1 -0
  89. package/backend/integrations/registry/providers/vercel.ts +1 -0
  90. package/backend/integrations/registry/types.ts +2 -0
  91. package/backend/memory/compose.ts +2 -2
  92. package/backend/memory/consolidate.ts +2 -2
  93. package/backend/memory/extract/episodic.ts +2 -2
  94. package/backend/memory/judge.ts +2 -2
  95. package/backend/profiles/service.ts +7 -6
  96. package/backend/push/sender.ts +172 -0
  97. package/backend/push/tags.ts +25 -0
  98. package/backend/push/vapid-keys.ts +77 -0
  99. package/backend/push/webpush-crypto.test.ts +200 -0
  100. package/backend/push/webpush-crypto.ts +231 -0
  101. package/backend/skills/detect.ts +28 -0
  102. package/backend/skills/index.ts +22 -4
  103. package/backend/skills/invoke.test.ts +114 -0
  104. package/backend/skills/invoke.ts +222 -0
  105. package/backend/skills/service.ts +194 -44
  106. package/backend/skills/spec.ts +35 -0
  107. package/backend/skills/sync.ts +85 -55
  108. package/backend/subagents/detect.ts +2 -3
  109. package/backend/subagents/sync.ts +15 -8
  110. package/backend/work/pull-requests.ts +2 -2
  111. package/backend/work/start-work.ts +4 -0
  112. package/backend/worktrees/branching/engine.ts +557 -0
  113. package/backend/worktrees/branching/index.ts +56 -0
  114. package/backend/worktrees/branching/naming.test.ts +118 -0
  115. package/backend/worktrees/branching/naming.ts +97 -0
  116. package/backend/worktrees/branching/projector.test.ts +229 -0
  117. package/backend/worktrees/branching/projector.ts +139 -0
  118. package/backend/worktrees/branching/providers/neon.ts +220 -0
  119. package/backend/worktrees/branching/registry.ts +27 -0
  120. package/backend/worktrees/branching/service.ts +620 -0
  121. package/backend/worktrees/branching/suggest.test.ts +154 -0
  122. package/backend/worktrees/branching/suggest.ts +202 -0
  123. package/backend/worktrees/branching/types.ts +88 -0
  124. package/backend/worktrees/index.ts +7 -0
  125. package/backend/worktrees/service.ts +48 -1
  126. package/backend/ws/chat/stream.ts +100 -8
  127. package/backend/ws/db-client/env.ts +142 -0
  128. package/backend/ws/db-client/index.ts +2 -0
  129. package/backend/ws/files/index.ts +4 -0
  130. package/backend/ws/files/share.ts +95 -0
  131. package/backend/ws/git/branch-name.ts +2 -2
  132. package/backend/ws/git/commit-message.ts +2 -2
  133. package/backend/ws/index.ts +3 -4
  134. package/backend/ws/profiles/crud.ts +2 -3
  135. package/backend/ws/projects/index.ts +6 -1
  136. package/backend/ws/projects/info.ts +70 -6
  137. package/backend/ws/projects/overview.test.ts +108 -0
  138. package/backend/ws/projects/overview.ts +300 -0
  139. package/backend/ws/skills/catalog.ts +5 -1
  140. package/backend/ws/skills/crud.ts +128 -22
  141. package/backend/ws/skills/index.ts +4 -1
  142. package/backend/ws/system/device-info.ts +307 -76
  143. package/backend/ws/user/crud.ts +12 -3
  144. package/backend/ws/worktrees/branching.ts +212 -0
  145. package/backend/ws/worktrees/crud.ts +33 -7
  146. package/backend/ws/worktrees/index.ts +14 -0
  147. package/dist/assets/{index-C8Gi-b6U.js → index-CeNKKSDR.js} +1 -1
  148. package/dist/assets/{index-BrF6nqld.js → index-DW89566K.js} +1 -1
  149. package/dist/assets/main-Cy5DXWPT.js +1207 -0
  150. package/dist/assets/main-DJKj_4By.css +1 -0
  151. package/dist/index.html +7 -2
  152. package/dist/sw.js +112 -0
  153. package/package.json +1 -1
  154. package/shared/constants/engine-tools.ts +31 -6
  155. package/shared/constants/notification-messages.ts +142 -0
  156. package/shared/constants/tool-icons.ts +6 -2
  157. package/shared/types/db-client/env.ts +192 -0
  158. package/shared/types/db-client/index.ts +1 -0
  159. package/shared/types/db-client/integrations.ts +30 -0
  160. package/shared/types/integrations.ts +9 -0
  161. package/shared/types/unified/stream.ts +7 -0
  162. package/shared/types/worktree-branching.ts +315 -0
  163. package/shared/utils/logger.ts +1 -0
  164. package/backend/commands/detect.ts +0 -25
  165. package/backend/commands/index.ts +0 -9
  166. package/backend/commands/service.ts +0 -178
  167. package/backend/commands/store.ts +0 -45
  168. package/backend/commands/sync.ts +0 -94
  169. package/backend/database/queries/command-queries.ts +0 -82
  170. package/backend/ws/commands/crud.ts +0 -157
  171. package/backend/ws/commands/index.ts +0 -8
  172. package/dist/assets/main-Bd3gb79F.css +0 -1
  173. package/dist/assets/main-Bo1hD7mt.js +0 -1191
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * Skill CRUD Handlers
3
3
  *
4
- * Manage user Agent Skills (Settings → Skills):
4
+ * Manage user Agent Skills (Settings → Skills) — one feature covering both
5
+ * model-invoked skills (`auto`) and user-invoked `/slash` prompts:
5
6
  * - skills:list — installed skills (DB metadata + on-disk presence)
6
7
  * - skills:get — one skill plus its SKILL.md body (for the editor)
7
8
  * - skills:create — author a skill from editor fields
@@ -10,17 +11,25 @@
10
11
  * - skills:import — persist a pasted/uploaded SKILL.md
11
12
  * - skills:toggle — enable / disable
12
13
  * - skills:delete — remove
14
+ * - skills:detect — on-disk skills (managed + adoptable) per engine
15
+ * - skills:adopt — link an adoptable on-disk skill into Clopen's engine dir
16
+ * - skills:available — slash-invocable skills for the chat "/" picker
13
17
  *
14
- * Mutations are admin-gated (see backend/auth/permissions.ts). Changes take
15
- * effect on the next chat stream, when each engine re-syncs its skills.
18
+ * Mutations are admin-gated (see backend/auth/permissions.ts) — except
19
+ * `skills:available`, which any user needs in order to type a command. Changes
20
+ * take effect on the next chat stream, when each engine re-syncs its skills.
16
21
  */
17
22
 
18
23
  import { t } from 'elysia';
19
24
  import { createRouter } from '$shared/utils/ws-server';
20
25
  import { debug } from '$shared/utils/logger';
21
- import { skillService } from '$backend/skills';
26
+ import { skillService, detectSkills, syncSkillsAllEngines } from '$backend/skills';
27
+ import { adoptArtifact, ARTIFACT_ENGINES, type ArtifactEngine } from '$backend/artifacts';
28
+ import { resolveActiveProfileId, artifactFilter } from '$backend/profiles';
29
+ import type { SkillTrigger } from '$backend/database/queries';
22
30
 
23
31
  const SOURCE_SCHEMA = t.Union([t.Literal('custom'), t.Literal('imported'), t.Literal('marketplace')]);
32
+ const TRIGGER_SCHEMA = t.Union([t.Literal('auto'), t.Literal('slash')]);
24
33
 
25
34
  const SKILL_SCHEMA = t.Object({
26
35
  id: t.Number(),
@@ -31,11 +40,59 @@ const SKILL_SCHEMA = t.Object({
31
40
  marketplaceRef: t.Union([t.String(), t.Null()]),
32
41
  version: t.Union([t.String(), t.Null()]),
33
42
  license: t.Union([t.String(), t.Null()]),
43
+ triggers: t.Array(TRIGGER_SCHEMA),
44
+ argumentHint: t.Union([t.String(), t.Null()]),
45
+ uses: t.Array(t.String()),
34
46
  enabled: t.Boolean(),
35
47
  present: t.Boolean(),
36
48
  createdAt: t.String()
37
49
  });
38
50
 
51
+ const FIELDS_SCHEMA = {
52
+ name: t.String(),
53
+ description: t.String(),
54
+ body: t.String(),
55
+ license: t.Optional(t.String()),
56
+ triggers: t.Optional(t.Array(TRIGGER_SCHEMA)),
57
+ argumentHint: t.Optional(t.Union([t.String(), t.Null()])),
58
+ uses: t.Optional(t.Array(t.String()))
59
+ };
60
+
61
+ const DETECTED_SCHEMA = t.Object({
62
+ engine: t.String(),
63
+ detected: t.Array(t.Object({
64
+ slug: t.String(),
65
+ name: t.String(),
66
+ description: t.String(),
67
+ path: t.String(),
68
+ managed: t.Boolean(),
69
+ adoptable: t.Boolean()
70
+ }))
71
+ });
72
+
73
+ /** Editor fields, with `triggers` narrowed back to the service's union type. */
74
+ function toInput(data: {
75
+ slug?: string;
76
+ name: string;
77
+ description: string;
78
+ body: string;
79
+ license?: string;
80
+ triggers?: string[];
81
+ argumentHint?: string | null;
82
+ uses?: string[];
83
+ }) {
84
+ return {
85
+ slug: data.slug,
86
+ name: data.name,
87
+ description: data.description,
88
+ body: data.body,
89
+ license: data.license,
90
+ triggers: data.triggers as SkillTrigger[] | undefined,
91
+ argumentHint: data.argumentHint,
92
+ uses: data.uses
93
+ };
94
+ }
95
+
39
96
  export const skillCrudHandler = createRouter()
40
97
  .http('skills:list', {
41
98
  data: t.Object({}),
@@ -54,34 +111,28 @@ export const skillCrudHandler = createRouter()
54
111
  return result;
55
112
  })
56
113
  .http('skills:create', {
57
- data: t.Object({
58
- name: t.String(),
59
- description: t.String(),
60
- body: t.String(),
61
- license: t.Optional(t.String())
62
- }),
114
+ // `slug` is create-only — see SkillInputFields for why it can't be renamed.
115
+ data: t.Object({ slug: t.Optional(t.String()), ...FIELDS_SCHEMA }),
63
116
  response: t.Object({ skill: SKILL_SCHEMA })
64
117
  }, async ({ data }) => {
65
118
  debug.log('path', `skills:create ${data.name}`);
66
119
  if (!data.name.trim()) throw new Error('A skill name is required');
67
120
  if (!data.description.trim()) throw new Error('A skill description is required');
68
- const skill = await skillService.create(data);
121
+ if (!data.body.trim()) throw new Error('Instructions are required');
122
+ const skill = await skillService.create(toInput(data));
123
+ await syncSkillsAllEngines();
69
124
  return { skill };
70
125
  })
71
126
  .http('skills:update', {
72
- data: t.Object({
73
- id: t.Number(),
74
- name: t.String(),
75
- description: t.String(),
76
- body: t.String(),
77
- license: t.Optional(t.String())
78
- }),
127
+ data: t.Object({ id: t.Number(), ...FIELDS_SCHEMA }),
79
128
  response: t.Object({ skill: SKILL_SCHEMA })
80
129
  }, async ({ data }) => {
81
130
  debug.log('path', `skills:update ${data.id}`);
82
131
  if (!data.name.trim()) throw new Error('A skill name is required');
83
132
  if (!data.description.trim()) throw new Error('A skill description is required');
84
- const skill = await skillService.update(data.id, data);
133
+ if (!data.body.trim()) throw new Error('Instructions are required');
134
+ const skill = await skillService.update(data.id, toInput(data));
135
+ await syncSkillsAllEngines();
85
136
  return { skill };
86
137
  })
87
138
  .http('skills:parse-import', {
@@ -91,6 +142,9 @@ export const skillCrudHandler = createRouter()
91
142
  name: t.String(),
92
143
  description: t.String(),
93
144
  license: t.Union([t.String(), t.Null()]),
145
+ triggers: t.Array(TRIGGER_SCHEMA),
146
+ argumentHint: t.Union([t.String(), t.Null()]),
147
+ uses: t.Array(t.String()),
94
148
  body: t.String(),
95
149
  warnings: t.Array(t.String())
96
150
  })
@@ -99,11 +153,12 @@ export const skillCrudHandler = createRouter()
99
153
  return skillService.parsePreview(data.text);
100
154
  })
101
155
  .http('skills:import', {
102
- data: t.Object({ text: t.String() }),
156
+ data: t.Object({ text: t.String(), name: t.Optional(t.String()) }),
103
157
  response: t.Object({ skill: SKILL_SCHEMA })
104
158
  }, async ({ data }) => {
105
159
  debug.log('path', 'skills:import');
106
- const skill = await skillService.import(data.text);
160
+ const skill = await skillService.import(data.text, data.name);
161
+ await syncSkillsAllEngines();
107
162
  return { skill };
108
163
  })
109
164
  .http('skills:toggle', {
@@ -111,7 +166,9 @@ export const skillCrudHandler = createRouter()
111
166
  response: t.Object({ skill: SKILL_SCHEMA })
112
167
  }, async ({ data }) => {
113
168
  debug.log('path', `skills:toggle ${data.id} → ${data.enabled}`);
114
- return { skill: skillService.toggle(data.id, data.enabled) };
169
+ const skill = skillService.toggle(data.id, data.enabled);
170
+ await syncSkillsAllEngines();
171
+ return { skill };
115
172
  })
116
173
  .http('skills:delete', {
117
174
  data: t.Object({ id: t.Number() }),
@@ -119,5 +176,54 @@ export const skillCrudHandler = createRouter()
119
176
  }, async ({ data }) => {
120
177
  debug.log('path', `skills:delete ${data.id}`);
121
178
  await skillService.remove(data.id);
179
+ await syncSkillsAllEngines();
122
180
  return { success: true };
181
+ })
182
+ .http('skills:detect', {
183
+ data: t.Object({ projectPath: t.Optional(t.String()) }),
184
+ response: t.Object({ groups: t.Array(DETECTED_SCHEMA) })
185
+ }, async ({ data }) => {
186
+ debug.log('path', 'skills:detect');
187
+ return { groups: await detectSkills(data.projectPath) };
188
+ })
189
+ .http('skills:adopt', {
190
+ // Link a skill the user already has on disk into Clopen's isolated engine
191
+ // dir, so it takes effect without relocating their file. `adoptArtifact`
192
+ // existed since the framework landed but had no caller — "detect" could
193
+ // only ever report, never act.
194
+ data: t.Object({ engine: t.String(), slug: t.String(), path: t.String() }),
195
+ response: t.Object({ linkedTo: t.String() })
196
+ }, async ({ data }) => {
197
+ debug.log('path', `skills:adopt ${data.engine}/${data.slug}`);
198
+ if (!ARTIFACT_ENGINES.includes(data.engine as ArtifactEngine)) {
199
+ throw new Error(`Unknown engine "${data.engine}"`);
200
+ }
201
+ const linkedTo = await adoptArtifact(
202
+ 'skill',
203
+ { engine: data.engine as ArtifactEngine, scope: 'global' },
204
+ data.path,
205
+ data.slug
206
+ );
207
+ return { linkedTo };
208
+ })
209
+ .http('skills:available', {
210
+ // Non-admin: slash-invocable skills for the chat "/" picker (display fields
211
+ // only), narrowed by the session's active profile same as stream sync.
212
+ data: t.Object({
213
+ profileId: t.Optional(t.Union([t.Number(), t.Null()])),
214
+ projectId: t.Optional(t.String())
215
+ }),
216
+ response: t.Object({
217
+ skills: t.Array(t.Object({
218
+ slug: t.String(),
219
+ name: t.String(),
220
+ description: t.String(),
221
+ argumentHint: t.Union([t.String(), t.Null()])
222
+ }))
223
+ })
224
+ }, async ({ data }) => {
225
+ debug.log('path', 'skills:available');
226
+ const activeProfileId = resolveActiveProfileId(data.profileId ?? null, data.projectId);
227
+ const filter = artifactFilter(activeProfileId, 'skill');
228
+ return { skills: skillService.available(filter) };
123
229
  });
@@ -1,8 +1,11 @@
1
1
  /**
2
2
  * Skills Router
3
3
  *
4
- * Entry point for user Agent Skill management (Settings → Skills):
4
+ * Entry point for user Agent Skill management (Settings → Skills) — one feature
5
+ * covering model-invoked skills and user-invoked `/slash` prompts:
5
6
  * - skills:list / get / create / update / import / toggle / delete — CRUD
7
+ * - skills:detect / adopt — on-disk skills, and linking one Clopen doesn't own
8
+ * - skills:available — the chat "/" picker (the one non-admin route here)
6
9
  * - skills:catalog / install — browse + install from a marketplace provider
7
10
  */
8
11
 
@@ -14,9 +14,11 @@
14
14
  * Static facts (OS, CPU model, core count, installed RAM, GPU model,
15
15
  * virtualization) come from `backend/host/metrics.ts`, which probes them once
16
16
  * per process and is also what Project Info reads, so the two panels cannot
17
- * disagree about the machine they are describing. Dynamic metrics (load,
18
- * memory in use, battery, disk, GPU utilization) are recomputed on every
19
- * request so the panel can poll live.
17
+ * disagree about the machine they are describing. Fast live metrics (CPU via
18
+ * OS deltas, memory, network, uptime) are re-read on every request so the
19
+ * panel polls live. Slow WMI-bound metrics (battery, disk usage, GPU) are
20
+ * cached for 60s and refreshed in the background, so one timed-out probe can
21
+ * never flip the panel between "This Device" <-> "Server" or drop cards.
20
22
  */
21
23
 
22
24
  import { t } from 'elysia';
@@ -26,14 +28,141 @@ import type { Systeminformation } from 'systeminformation';
26
28
  import { createRouter } from '$shared/utils/ws-server';
27
29
  import { getHostFacts, withTimeout } from '../../host/metrics';
28
30
 
29
- /** Last-good caches for dynamic probes: prevents transient WMI timeouts from
30
- * flickering the UI between "This Device" <-> "Server" or dropping Storage cards. */
31
- let lastMemCache: Systeminformation.MemData | null = null;
32
- let lastBatteryCache: Systeminformation.BatteryData | null = null;
33
- let lastFsSizeCache: Systeminformation.FsSizeData[] | null = null;
34
- let lastLoadCache: Systeminformation.CurrentLoadData | null = null;
35
- let lastGraphicsCache: Systeminformation.GraphicsData | null = null;
36
- let lastNetCache: Systeminformation.NetworkInterfacesData | null = null;
31
+ /** Two-tier probing. Fast signals (CPU via os deltas, memory, network, uptime)
32
+ * are cheap and re-read on every request. Slow signals (battery, disk usage,
33
+ * GPU) shell out to WMI/PowerShell, change slowly, and time out under load —
34
+ * re-probing them on every poll is what made the panel flip between
35
+ * "This Device" <-> "Server" and made Battery/Swap/Storage cards appear and
36
+ * vanish on every open/close. Slow signals are cached for SLOW_TTL_MS and
37
+ * refreshed in the background; a request only waits for them on cold start
38
+ * when no snapshot exists at all. */
39
+ const LAST_GOOD_MAX_AGE_MS = 60_000;
40
+ const SLOW_TTL_MS = 60_000;
41
+ interface TimedCache<T> { value: T; at: number }
42
+ let lastMemCache: TimedCache<Systeminformation.MemData> | null = null;
43
+ let lastNetCache: TimedCache<Systeminformation.NetworkInterfacesData> | null = null;
44
+
45
+ function fresh<T>(cache: TimedCache<T> | null): T | null {
46
+ if (!cache || Date.now() - cache.at > LAST_GOOD_MAX_AGE_MS) return null;
47
+ return cache.value;
48
+ }
49
+
50
+ interface SlowSnapshot {
51
+ battery: Systeminformation.BatteryData | null;
52
+ fsSize: Systeminformation.FsSizeData[] | null;
53
+ graphics: Systeminformation.GraphicsData | null;
54
+ at: number;
55
+ }
56
+ let slowCache: SlowSnapshot | null = null;
57
+ let slowInFlight: Promise<SlowSnapshot> | null = null;
58
+
59
+ /** Battery presence is sticky: WMI transiently reports no-battery/timeout on
60
+ * laptops under load, which used to flip the whole panel to "Server". Only
61
+ * three consecutive *explicit* no-battery readings (not timeouts) clear it. */
62
+ let stickyHasBattery = false;
63
+ let batteryFalseStreak = 0;
64
+
65
+ async function probeSlow(): Promise<SlowSnapshot> {
66
+ const [battery, graphics, fsSize] = await Promise.all([
67
+ withTimeout(si.battery(), 8000),
68
+ withTimeout(si.graphics(), 8000),
69
+ withTimeout(si.fsSize(), 8000)
70
+ ]);
71
+ if (battery) {
72
+ if (battery.hasBattery) {
73
+ stickyHasBattery = true;
74
+ batteryFalseStreak = 0;
75
+ } else if (++batteryFalseStreak >= 3) {
76
+ stickyHasBattery = false;
77
+ }
78
+ }
79
+ const snapshot: SlowSnapshot = { battery, fsSize, graphics, at: Date.now() };
80
+ // Merge: never let one timed-out probe wipe a good snapshot from another.
81
+ if (slowCache) {
82
+ if (!snapshot.battery) snapshot.battery = slowCache.battery;
83
+ if (!snapshot.fsSize) snapshot.fsSize = slowCache.fsSize;
84
+ if (!snapshot.graphics) snapshot.graphics = slowCache.graphics;
85
+ }
86
+ slowCache = snapshot;
87
+ return snapshot;
88
+ }
89
+
90
+ /** Slow signals for one request: fresh cache served instantly, stale cache
91
+ * served instantly while a background refresh runs, cold start awaits. */
92
+ function ensureSlow(): Promise<SlowSnapshot> {
93
+ if (slowCache && Date.now() - slowCache.at < SLOW_TTL_MS) {
94
+ return Promise.resolve(slowCache);
95
+ }
96
+ if (slowInFlight) return slowInFlight;
97
+ slowInFlight = probeSlow().then((snapshot) => {
98
+ slowInFlight = null;
99
+ return snapshot;
100
+ });
101
+ slowInFlight.then(
102
+ () => {},
103
+ () => {
104
+ slowInFlight = null;
105
+ }
106
+ );
107
+ // Stale-but-usable snapshot wins over waiting: the Device tab must open
108
+ // instantly with consistent cards, then correct itself next poll.
109
+ if (slowCache) return Promise.resolve(slowCache);
110
+ return slowInFlight;
111
+ }
112
+
113
+ /** Rolling OS-level CPU measurement (same source Task Manager samples).
114
+ * `si.currentLoad()` on a cold process — especially while 11 WMI/PowerShell
115
+ * probes run concurrently — can spike to 100%, and the spike is partly the
116
+ * measurement storm itself. Sampling `os.cpus()` deltas between requests
117
+ * (one per uncached request) measures the real machine load instead. */
118
+ let lastCpuSample: { busy: number; total: number; at: number } | null = null;
119
+ let lastCpuPercent: number | null = null;
120
+ /** A delta is an average over the gap between samples. Across a closed panel
121
+ * that gap is minutes, and the resulting figure describes a window nobody
122
+ * asked about — so an old baseline is dropped and re-seeded instead. */
123
+ const MAX_CPU_SAMPLE_GAP_MS = 15_000;
124
+
125
+ function sampleOsCpuPercent(): number | null {
126
+ let busy = 0;
127
+ let total = 0;
128
+ // Containers with no readable per-core stats report an empty list; there is
129
+ // nothing to difference, so the si probe stays the source for that host.
130
+ for (const core of os.cpus()) {
131
+ const active = core.times.user + core.times.nice + core.times.sys + core.times.irq;
132
+ busy += active;
133
+ total += active + core.times.idle;
134
+ }
135
+ const now = Date.now();
136
+ const prev = lastCpuSample;
137
+ lastCpuSample = total > 0 ? { busy, total, at: now } : null;
138
+
139
+ if (prev && now - prev.at > MAX_CPU_SAMPLE_GAP_MS) {
140
+ // Re-seeded above; this tick falls back to si.currentLoad() and the
141
+ // next one has a baseline worth differencing.
142
+ lastCpuPercent = null;
143
+ return null;
144
+ }
145
+ if (prev && now - prev.at >= 500 && total - prev.total > 0) {
146
+ const pct = ((busy - prev.busy) / (total - prev.total)) * 100;
147
+ lastCpuPercent = Math.min(100, Math.max(0, pct));
148
+ }
149
+ return lastCpuPercent;
150
+ }
151
+
152
+ /** OS fallback for the default network interface when `si` returns nothing
153
+ * (e.g. transient WMI timeout): first up, non-internal IPv4 interface. */
154
+ function osFallbackNetwork(): { iface: string; ip4: string; mac: string } | null {
155
+ const ifaces = os.networkInterfaces();
156
+ for (const [name, addrs] of Object.entries(ifaces)) {
157
+ for (const addr of addrs ?? []) {
158
+ if (addr.internal || addr.family !== 'IPv4' || !addr.address) continue;
159
+ // Skip virtual/tunnel adapters without a real MAC.
160
+ if (!addr.mac || addr.mac === '00:00:00:00:00:00') continue;
161
+ return { iface: name, ip4: addr.address, mac: addr.mac };
162
+ }
163
+ }
164
+ return null;
165
+ }
37
166
 
38
167
  const GpuSchema = t.Object({
39
168
  model: t.String(),
@@ -129,74 +258,111 @@ function selectPrimaryDisks(raw: Systeminformation.FsSizeData[], platform: strin
129
258
  .sort((a, b) => (a.mount === '/' ? -1 : b.mount === '/' ? 1 : b.sizeBytes - a.sizeBytes));
130
259
  }
131
260
 
132
- export const deviceInfoHandler = createRouter()
133
- .http('system:device-info', {
134
- data: t.Object({}),
135
- response: t.Object({
136
- hostname: t.String(),
137
- platform: t.String(),
138
- distro: t.String(),
139
- release: t.String(),
140
- kernel: t.String(),
141
- arch: t.String(),
142
- isVirtual: t.Boolean(),
143
- uptimeSec: t.Number(),
144
- cpu: t.Object({
145
- brand: t.String(),
146
- manufacturer: t.String(),
147
- physicalCores: t.Number(),
148
- logicalCores: t.Number(),
149
- speedGhz: t.Union([t.Number(), t.Null()]),
150
- loadPercent: t.Number(),
151
- loadAvg1: t.Union([t.Number(), t.Null()])
152
- }),
153
- memory: t.Object({
154
- totalBytes: t.Number(),
155
- usedBytes: t.Number(),
156
- freeBytes: t.Number(),
157
- swapTotalBytes: t.Number(),
158
- swapUsedBytes: t.Number()
159
- }),
160
- network: t.Object({
161
- iface: t.String(),
162
- ip4: t.String(),
163
- mac: t.String()
164
- }),
165
- battery: BatterySchema,
166
- gpus: t.Array(GpuSchema),
167
- disks: t.Array(DiskSchema)
168
- })
169
- }, async () => {
170
- const facts = await getHostFacts();
261
+ /** Response snapshot served from cache inside the TTL so a burst of opens
262
+ * and rapid tab switches never re-run the si.* probes. */
263
+ interface DeviceInfoPayload {
264
+ hostname: string;
265
+ platform: string;
266
+ distro: string;
267
+ release: string;
268
+ kernel: string;
269
+ arch: string;
270
+ isVirtual: boolean;
271
+ uptimeSec: number;
272
+ cpu: {
273
+ brand: string;
274
+ manufacturer: string;
275
+ physicalCores: number;
276
+ logicalCores: number;
277
+ speedGhz: number | null;
278
+ loadPercent: number;
279
+ loadAvg1: number | null;
280
+ };
281
+ memory: {
282
+ totalBytes: number;
283
+ usedBytes: number;
284
+ freeBytes: number;
285
+ swapTotalBytes: number;
286
+ swapUsedBytes: number;
287
+ };
288
+ network: { iface: string; ip4: string; mac: string };
289
+ battery: {
290
+ hasBattery: boolean;
291
+ percent: number | null;
292
+ isCharging: boolean;
293
+ acConnected: boolean;
294
+ timeRemainingMinutes: number | null;
295
+ };
296
+ gpus: Array<{
297
+ model: string;
298
+ vendor: string;
299
+ vramMb: number | null;
300
+ utilizationGpu: number | null;
301
+ memoryUsedMb: number | null;
302
+ memoryTotalMb: number | null;
303
+ }>;
304
+ disks: DiskInfo[];
305
+ }
306
+
307
+ /** Comfortably under the frontend's 3s heartbeat. At an equal TTL, jitter
308
+ * means roughly every other poll is answered with the payload it already
309
+ * has, so a panel advertising live numbers would really move every 6s. */
310
+ const DEVICE_CACHE_TTL_MS = 1500;
311
+ let cachedDevice: { payload: DeviceInfoPayload; at: number } | null = null;
312
+ let inFlightDevice: Promise<DeviceInfoPayload> | null = null;
313
+
314
+ async function buildDeviceInfo(): Promise<DeviceInfoPayload> {
315
+ // Static facts and live probes launch together. They used to run one
316
+ // after another (facts ~4s cold, then probes ~3.5s), which stacked past
317
+ // 7s on first open while other settings tabs render instantly.
318
+ // Concurrent, the slowest single phase bounds the total.
319
+ const factsP = getHostFacts();
171
320
 
172
- const [load, mem, battery, graphics, fsSize, netDefault] = await Promise.all([
173
- withTimeout(si.currentLoad(), 3500),
321
+ // OS-level CPU sample taken at request start; the delta is measured
322
+ // against the previous uncached request, free of probe overhead.
323
+ const osCpuPercent = sampleOsCpuPercent();
324
+
325
+ // Per-poll storm cut from ~11 concurrent spawns to 3: only CPU
326
+ // fallback, memory, and network run here. Battery/disks/GPU come
327
+ // from the slow tier so one WMI timeout can no longer flip cards
328
+ // or inflate the CPU reading with its own measurement cost.
329
+ const dynamicP = Promise.all([
330
+ // si CPU is only a first-poll fallback; once the OS delta has a
331
+ // baseline it is both cheaper and more accurate, so skip the spawn.
332
+ osCpuPercent !== null
333
+ ? Promise.resolve(null)
334
+ : withTimeout(si.currentLoad(), 3500),
174
335
  withTimeout(si.mem(), 3500),
175
- withTimeout(si.battery(), 3500),
176
- withTimeout(si.graphics(), 3500),
177
- withTimeout(si.fsSize(), 3500),
178
- withTimeout(si.networkInterfaces('default'), 3500)
336
+ withTimeout(si.networkInterfaces('default'), 3500),
337
+ ensureSlow()
338
+ ]);
339
+
340
+ const [facts, [load, mem, netDefault, slow]] = await Promise.all([
341
+ factsP,
342
+ dynamicP
179
343
  ]);
180
344
 
181
345
  // Update last-good caches; reuse them when a probe times out so the UI
182
346
  // doesn't flicker between "This Device" <-> "Server" or drop Storage cards.
183
- if (mem) lastMemCache = mem;
184
- if (battery) lastBatteryCache = battery;
185
- if (fsSize) lastFsSizeCache = fsSize;
186
- if (load) lastLoadCache = load;
187
- if (graphics) lastGraphicsCache = graphics;
188
- if (netDefault) lastNetCache = Array.isArray(netDefault) ? netDefault[0] : netDefault;
189
-
190
- const memEff = mem ?? lastMemCache;
191
- const batteryEff = battery ?? lastBatteryCache;
192
- const fsSizeEff = fsSize ?? lastFsSizeCache ?? [];
193
- const loadEff = load ?? lastLoadCache;
194
- const graphicsEff = graphics ?? lastGraphicsCache;
195
- const netRawEff = netDefault ?? lastNetCache;
196
- const net = Array.isArray(netRawEff) ? netRawEff[0] : netRawEff;
197
-
198
- // avgLoad is 0/undefined on platforms without load average (e.g. Windows).
199
- const loadAvg1 = typeof loadEff?.avgLoad === 'number' && loadEff.avgLoad > 0 ? loadEff.avgLoad : null;
347
+ // Stale entries (>60s) are ignored so timed-out probes can't pin old
348
+ // numbers as live device state forever.
349
+ const now = Date.now();
350
+ if (mem) lastMemCache = { value: mem, at: now };
351
+ if (netDefault) lastNetCache = { value: Array.isArray(netDefault) ? netDefault[0] : netDefault, at: now };
352
+
353
+ const memEff = mem ?? fresh(lastMemCache);
354
+ const batteryEff = slow.battery;
355
+ const fsSizeEff = slow.fsSize ?? [];
356
+ const graphicsEff = slow.graphics;
357
+ const netRawEff = netDefault ?? fresh(lastNetCache);
358
+ const netSi = Array.isArray(netRawEff) ? netRawEff[0] : netRawEff;
359
+ const netOsFallback = !netSi?.ip4 ? osFallbackNetwork() : null;
360
+ const net = netSi?.ip4 ? netSi : netOsFallback;
361
+
362
+ // Authoritative 1-minute load average straight from the OS (zeros on
363
+ // Windows → null, same as before, but without waiting on si timing).
364
+ const osAvg1 = os.loadavg()[0];
365
+ const loadAvg1 = typeof osAvg1 === 'number' && osAvg1 > 0 ? osAvg1 : null;
200
366
 
201
367
  // Pair live GPU utilization with the cached controller identity by index.
202
368
  const gpus = facts.gpus.map((g, i) => {
@@ -231,7 +397,9 @@ export const deviceInfoHandler = createRouter()
231
397
  speedGhz: facts.cpuSpeedGhz,
232
398
  // Percent of total machine capacity — the same basis Project Info
233
399
  // normalises its per-project figure to, so the two are comparable.
234
- loadPercent: typeof loadEff?.currentLoad === 'number' ? loadEff.currentLoad : 0,
400
+ // OS-delta first (immune to the si cold-start spike and to the
401
+ // probe storm's own CPU cost), si reading as fallback.
402
+ loadPercent: osCpuPercent ?? (typeof load?.currentLoad === 'number' ? load.currentLoad : 0),
235
403
  loadAvg1
236
404
  },
237
405
  memory: {
@@ -249,8 +417,12 @@ export const deviceInfoHandler = createRouter()
249
417
  mac: net?.mac || ''
250
418
  },
251
419
  battery: {
252
- hasBattery: Boolean(batteryEff?.hasBattery),
253
- percent: typeof batteryEff?.percent === 'number' && batteryEff.hasBattery ? batteryEff.percent : null,
420
+ // Sticky presence: a single timed-out/no-battery WMI read must
421
+ // not flip the panel to "Server" on a laptop with a battery.
422
+ hasBattery: stickyHasBattery || Boolean(batteryEff?.hasBattery),
423
+ // Rounded to a whole percent like the OS taskbar/menu-bar shows;
424
+ // si can report floats on some platforms (e.g. 27.6 → 28).
425
+ percent: typeof batteryEff?.percent === 'number' && batteryEff.hasBattery ? Math.round(batteryEff.percent) : null,
254
426
  isCharging: Boolean(batteryEff?.isCharging),
255
427
  acConnected: Boolean(batteryEff?.acConnected),
256
428
  timeRemainingMinutes:
@@ -261,4 +433,63 @@ export const deviceInfoHandler = createRouter()
261
433
  gpus,
262
434
  disks
263
435
  };
436
+ }
437
+
438
+ function getDeviceInfo(): Promise<DeviceInfoPayload> {
439
+ if (cachedDevice && Date.now() - cachedDevice.at < DEVICE_CACHE_TTL_MS) {
440
+ return Promise.resolve(cachedDevice.payload);
441
+ }
442
+ if (inFlightDevice) return inFlightDevice;
443
+
444
+ inFlightDevice = buildDeviceInfo().then((payload) => {
445
+ cachedDevice = { payload, at: Date.now() };
446
+ inFlightDevice = null;
447
+ return payload;
264
448
  });
449
+ inFlightDevice.then(
450
+ () => {},
451
+ () => {
452
+ inFlightDevice = null;
453
+ }
454
+ );
455
+ return inFlightDevice;
456
+ }
457
+
458
+ export const deviceInfoHandler = createRouter()
459
+ .http('system:device-info', {
460
+ data: t.Object({}),
461
+ response: t.Object({
462
+ hostname: t.String(),
463
+ platform: t.String(),
464
+ distro: t.String(),
465
+ release: t.String(),
466
+ kernel: t.String(),
467
+ arch: t.String(),
468
+ isVirtual: t.Boolean(),
469
+ uptimeSec: t.Number(),
470
+ cpu: t.Object({
471
+ brand: t.String(),
472
+ manufacturer: t.String(),
473
+ physicalCores: t.Number(),
474
+ logicalCores: t.Number(),
475
+ speedGhz: t.Union([t.Number(), t.Null()]),
476
+ loadPercent: t.Number(),
477
+ loadAvg1: t.Union([t.Number(), t.Null()])
478
+ }),
479
+ memory: t.Object({
480
+ totalBytes: t.Number(),
481
+ usedBytes: t.Number(),
482
+ freeBytes: t.Number(),
483
+ swapTotalBytes: t.Number(),
484
+ swapUsedBytes: t.Number()
485
+ }),
486
+ network: t.Object({
487
+ iface: t.String(),
488
+ ip4: t.String(),
489
+ mac: t.String()
490
+ }),
491
+ battery: BatterySchema,
492
+ gpus: t.Array(GpuSchema),
493
+ disks: t.Array(DiskSchema)
494
+ })
495
+ }, async () => getDeviceInfo());