@vivix-labs/studio-workbench 1.0.0-beta.14 → 1.0.0-beta.17

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.
@@ -2,7 +2,8 @@ import { execFile, spawn } from 'node:child_process';
2
2
  import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
3
  import { homedir } from 'node:os';
4
4
  import { basename, dirname, join, resolve } from 'node:path';
5
- import { parseArgs, promisify } from 'node:util';
5
+ import { setTimeout as delay } from 'node:timers/promises';
6
+ import { isDeepStrictEqual, parseArgs, promisify } from 'node:util';
6
7
 
7
8
  const exec = promisify(execFile);
8
9
  const { values } = parseArgs({
@@ -97,6 +98,184 @@ async function warmDramaWorkbenches() {
97
98
  await cli('preset', 'warm-client', `${name}@${version}:${id}`);
98
99
  }
99
100
 
101
+ function sameSet(actual = [], expected = []) {
102
+ const a = new Set(actual);
103
+ const b = new Set(expected);
104
+ return a.size === b.size && [...a].every((item) => b.has(item));
105
+ }
106
+
107
+ function legacyPackageName(name) {
108
+ return name.startsWith('@vivix-labs/') ? '@vivix/' + name.slice('@vivix-labs/'.length) : name;
109
+ }
110
+
111
+ function planUserBaseUpdate(userBase, snapshot, globalPackages, userInstances) {
112
+ const composition = structuredClone(snapshot.composition);
113
+ const lock = structuredClone(snapshot.lock);
114
+ const existingById = new Map(composition.plugins.map((item) => [item.id, item]));
115
+ const runningById = new Map(userInstances.map((item) => [item.id, item]));
116
+ const installedByKey = new Map(
117
+ globalPackages.map((item) => [`${item.package}@${item.version}`, item]),
118
+ );
119
+ const managedIds = new Set(userBase.plugins.map((item) => item.id));
120
+ let changed = false;
121
+ const managedPlugins = [];
122
+ const verifiedTargets = [];
123
+
124
+ for (const target of userBase.plugins) {
125
+ const existing = existingById.get(target.id);
126
+ const previousLock = lock.instances[target.id];
127
+ // Preserve intentionally disabled plugins and existing `data` providers managed by upgrade-data.mjs.
128
+ if (existing && (existing.enabled === false || (target.id === 'data' && previousLock))) {
129
+ managedPlugins.push(existing);
130
+ continue;
131
+ }
132
+ const installed = installedByKey.get(`${target.package}@${target.version}`);
133
+ if (!installed?.integrity)
134
+ throw Error(`Required Studio plugin is not installed: ${target.package}@${target.version}.`);
135
+ if (
136
+ existing &&
137
+ existing.package !== target.package &&
138
+ existing.package !== legacyPackageName(target.package)
139
+ )
140
+ throw Error(
141
+ `Cannot upgrade Studio workspace: instance "${target.id}" belongs to ${existing.package}.`,
142
+ );
143
+ const access = [
144
+ ...new Set([...(previousLock?.access ?? []), ...(target.requiredAccess ?? [])]),
145
+ ];
146
+ const running = runningById.get(target.id);
147
+ if (
148
+ !existing ||
149
+ existing.package !== target.package ||
150
+ existing.enabled !== target.enabled ||
151
+ !isDeepStrictEqual(existing.config, target.config) ||
152
+ previousLock?.package !== target.package ||
153
+ previousLock?.version !== target.version ||
154
+ previousLock?.integrity !== installed.integrity ||
155
+ !sameSet(previousLock?.access, access) ||
156
+ running?.state !== 'ready'
157
+ )
158
+ changed = true;
159
+
160
+ managedPlugins.push({
161
+ id: target.id,
162
+ package: target.package,
163
+ enabled: target.enabled,
164
+ config: structuredClone(target.config),
165
+ });
166
+ verifiedTargets.push(target);
167
+ lock.instances[target.id] = {
168
+ package: target.package,
169
+ version: target.version,
170
+ integrity: installed.integrity,
171
+ access,
172
+ };
173
+ }
174
+
175
+ composition.plugins = [
176
+ ...managedPlugins,
177
+ ...composition.plugins.filter((item) => !managedIds.has(item.id)),
178
+ ];
179
+ const expectedBasedOn = {
180
+ package: userPackage.name,
181
+ version: userPackage.version,
182
+ presetId: userBase.id,
183
+ };
184
+ if (!isDeepStrictEqual(composition.basedOn, expectedBasedOn)) {
185
+ composition.basedOn = expectedBasedOn;
186
+ changed = true;
187
+ }
188
+ if (!composition.workspace && userBase.workspace) {
189
+ composition.workspace = structuredClone(userBase.workspace);
190
+ changed = true;
191
+ } else if (
192
+ userBase.workspace?.frontend &&
193
+ !isDeepStrictEqual(composition.workspace?.frontend, userBase.workspace.frontend)
194
+ ) {
195
+ composition.workspace = {
196
+ ...composition.workspace,
197
+ frontend: structuredClone(userBase.workspace.frontend),
198
+ settings: composition.workspace?.settings ?? {},
199
+ };
200
+ changed = true;
201
+ }
202
+ return { changed, composition, lock, verifiedTargets };
203
+ }
204
+
205
+ async function confirmRunningHost() {
206
+ const host = await read(join(root, 'runtime/host.json'));
207
+ const origin = new URL(host.origin);
208
+ if (
209
+ origin.protocol !== 'http:' ||
210
+ origin.hostname !== '127.0.0.1' ||
211
+ origin.pathname !== '/' ||
212
+ origin.username ||
213
+ origin.password ||
214
+ origin.search ||
215
+ origin.hash ||
216
+ typeof host.token !== 'string' ||
217
+ host.token.length < 20 ||
218
+ host.pid !== (await cli('host', 'status')).pid
219
+ )
220
+ throw Error('Cannot confirm the running Studio Host.');
221
+ return host;
222
+ }
223
+
224
+ async function postUserConfiguration(composition, lock, expectedRevision) {
225
+ const host = await confirmRunningHost();
226
+ const response = await fetch(host.origin + '/v1/user/configure', {
227
+ method: 'POST',
228
+ headers: { Authorization: 'Bearer ' + host.token, 'Content-Type': 'application/json' },
229
+ body: JSON.stringify({ composition, lock, expectedRevision }),
230
+ redirect: 'error',
231
+ signal: AbortSignal.timeout(300000),
232
+ });
233
+ const reply = await response.json();
234
+ if (!response.ok || !reply.ok)
235
+ throw Object.assign(Error(reply.error?.message || 'Workspace upgrade failed.'), {
236
+ code: reply.error?.code,
237
+ });
238
+ }
239
+
240
+ async function reconcileUserBase() {
241
+ const userBase = await read(new URL('../../presets/user-base.json', import.meta.url));
242
+ const [user, snapshot, globalReply] = await Promise.all([
243
+ cli('plugin', 'list', '--scope', 'user'),
244
+ cli('project', 'inspect', '--scope', 'user'),
245
+ cli('plugin', 'list', '--global'),
246
+ ]);
247
+ const plan = planUserBaseUpdate(userBase, snapshot, globalReply.packages, user.instances);
248
+ if (!plan.changed) return;
249
+
250
+ try {
251
+ await postUserConfiguration(plan.composition, plan.lock, snapshot.composition.revision);
252
+ } catch (error) {
253
+ if (error.code !== 'USER_SCOPE_IN_USE') throw error;
254
+ await cli('host', 'stop');
255
+ for (let i = 0; (await cli('host', 'status')).pid; i++) {
256
+ if (i === 60)
257
+ throw Error('Studio Host is still stopping. Rerun initialization after it exits.');
258
+ await delay(500);
259
+ }
260
+ await cli('plugin', 'list', '--scope', 'user');
261
+ await postUserConfiguration(plan.composition, plan.lock, snapshot.composition.revision);
262
+ }
263
+
264
+ const after = await cli('plugin', 'list', '--scope', 'user');
265
+ for (const target of plan.verifiedTargets) {
266
+ const current = after.instances.find((item) => item.id === target.id);
267
+ if (
268
+ !current ||
269
+ current.state !== 'ready' ||
270
+ current.package !== target.package ||
271
+ current.version !== target.version
272
+ )
273
+ throw Error(
274
+ `Studio user plugin ${target.id} did not become ready: ${current?.reason || 'missing'}`,
275
+ );
276
+ }
277
+ }
278
+
100
279
  async function configureDramaChat(projectId) {
101
280
  // Trial setup can enable chat before the on-demand drama project exists.
102
281
  const user = await cli('plugin', 'list', '--scope', 'user');
@@ -189,6 +368,8 @@ try {
189
368
  }
190
369
  state.workspace = true;
191
370
  await save();
371
+ } else if (!sample) {
372
+ await reconcileUserBase();
192
373
  }
193
374
  if (sample) {
194
375
  assertRunning();