@myrialabs/clopen 0.3.16 → 0.3.18

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.
@@ -0,0 +1,23 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Add workspace_state to user_projects for per-project dock/layout restore';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Adding workspace_state to user_projects...');
8
+ db.exec(`ALTER TABLE user_projects ADD COLUMN workspace_state TEXT`);
9
+ debug.log('migration', 'workspace_state column added');
10
+ };
11
+
12
+ export const down = (db: DatabaseConnection): void => {
13
+ debug.log('migration', 'Removing workspace_state from user_projects...');
14
+ db.exec(`
15
+ CREATE TABLE user_projects_backup AS
16
+ SELECT user_id, project_id, joined_at, current_session_id, files_panel_state FROM user_projects
17
+ `);
18
+ db.exec(`DROP TABLE user_projects`);
19
+ db.exec(`ALTER TABLE user_projects_backup RENAME TO user_projects`);
20
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_user_projects_user_id ON user_projects(user_id)`);
21
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_user_projects_project_id ON user_projects(project_id)`);
22
+ debug.log('migration', 'workspace_state column removed');
23
+ };
@@ -36,6 +36,7 @@ import * as migration034 from './034_seed_qwen_provider';
36
36
  import * as migration035 from './035_add_owner_to_db_client_connections';
37
37
  import * as migration036 from './036_create_auth_audit_log';
38
38
  import * as migration037 from './037_repair_auth_audit_log_schema';
39
+ import * as migration038 from './038_add_workspace_state_to_user_projects';
39
40
 
40
41
  // Export all migrations in order
41
42
  export const migrations = [
@@ -260,6 +261,12 @@ export const migrations = [
260
261
  description: migration037.description,
261
262
  up: migration037.up,
262
263
  down: migration037.down
264
+ },
265
+ {
266
+ id: '038',
267
+ description: migration038.description,
268
+ up: migration038.up,
269
+ down: migration038.down
263
270
  }
264
271
  ];
265
272
 
@@ -138,5 +138,23 @@ export const projectQueries = {
138
138
  SET files_panel_state = ?
139
139
  WHERE user_id = ? AND project_id = ?
140
140
  `).run(state, userId, projectId);
141
+ },
142
+
143
+ getWorkspaceState(userId: string, projectId: string): string | null {
144
+ const db = getDatabase();
145
+ const result = db.prepare(`
146
+ SELECT workspace_state FROM user_projects
147
+ WHERE user_id = ? AND project_id = ?
148
+ `).get(userId, projectId) as { workspace_state: string | null } | null;
149
+ return result?.workspace_state || null;
150
+ },
151
+
152
+ setWorkspaceState(userId: string, projectId: string, state: string | null): void {
153
+ const db = getDatabase();
154
+ db.prepare(`
155
+ UPDATE user_projects
156
+ SET workspace_state = ?
157
+ WHERE user_id = ? AND project_id = ?
158
+ `).run(state, userId, projectId);
141
159
  }
142
160
  };
@@ -0,0 +1,396 @@
1
+ /**
2
+ * Image Processing
3
+ *
4
+ * Applies an `ImageEditRecipe` to an image on disk using sharp and returns the
5
+ * encoded result as a Buffer. The client editor only ever sends a small
6
+ * declarative recipe — the full-resolution original is read here so quality is
7
+ * never bounded by what the browser downscaled for preview.
8
+ *
9
+ * Geometry is deterministic: for static images we fully bake rotate/flip into a
10
+ * raw intermediate buffer first, so the crop rectangle always maps to the
11
+ * orientation the user cropped against (sharp's single-pipeline op ordering is
12
+ * not call-order, so we stage it ourselves). Animated images (GIF/WebP) are
13
+ * processed in a single `{ animated: true }` pass to preserve their frames.
14
+ */
15
+
16
+ import sharp from 'sharp';
17
+ import type { Sharp } from 'sharp';
18
+
19
+ import type { ImageEditRecipe, ImageEditRegion, ImageEditStroke } from '$shared/types/filesystem';
20
+ import { validateFileSize } from './file-size-limit';
21
+
22
+ export interface ProcessedImage {
23
+ data: Buffer;
24
+ format: string;
25
+ width: number;
26
+ height: number;
27
+ size: number;
28
+ }
29
+
30
+ /** Clamp a value into [min, max], rounding to an integer. */
31
+ function clampInt(value: number, min: number, max: number): number {
32
+ return Math.max(min, Math.min(max, Math.round(value)));
33
+ }
34
+
35
+ /** Apply the color/tone adjustments shared by both processing paths. */
36
+ function applyColor(pipeline: Sharp, recipe: ImageEditRecipe): Sharp {
37
+ let p = pipeline;
38
+ if (recipe.background) {
39
+ // Composite any transparency onto a solid colour (e.g. for JPEG export).
40
+ p = p.flatten({ background: recipe.background });
41
+ }
42
+ if (recipe.grayscale) {
43
+ p = p.grayscale();
44
+ }
45
+ const brightness = recipe.brightness ?? 1;
46
+ const saturation = recipe.saturation ?? 1;
47
+ const hue = Math.round(recipe.hue ?? 0);
48
+ if (brightness !== 1 || saturation !== 1 || hue !== 0) {
49
+ p = p.modulate({ brightness, saturation, hue });
50
+ }
51
+ if (recipe.contrast != null && recipe.contrast !== 1) {
52
+ // Linear contrast around the 128 midpoint: out = slope*in + intercept.
53
+ p = p.linear(recipe.contrast, -(128 * recipe.contrast) + 128);
54
+ }
55
+ if (recipe.sepia) {
56
+ // Standard sepia matrix (matches the CSS `sepia(1)` filter).
57
+ p = p.recomb([
58
+ [0.393, 0.769, 0.189],
59
+ [0.349, 0.686, 0.168],
60
+ [0.272, 0.534, 0.131]
61
+ ]);
62
+ }
63
+ if (recipe.invert) {
64
+ p = p.negate({ alpha: false });
65
+ }
66
+ if (recipe.blur != null && recipe.blur > 0) {
67
+ p = p.blur(Math.max(0.3, recipe.blur));
68
+ }
69
+ return p;
70
+ }
71
+
72
+ /** True when the recipe applies any geometry, color, region or annotation change. */
73
+ function hasEdits(recipe: ImageEditRecipe): boolean {
74
+ return (
75
+ !!recipe.crop ||
76
+ !!recipe.resize ||
77
+ !!recipe.rotate ||
78
+ !!recipe.flipH ||
79
+ !!recipe.flipV ||
80
+ (recipe.brightness != null && recipe.brightness !== 1) ||
81
+ (recipe.saturation != null && recipe.saturation !== 1) ||
82
+ (recipe.contrast != null && recipe.contrast !== 1) ||
83
+ (recipe.hue != null && recipe.hue !== 0) ||
84
+ (recipe.blur != null && recipe.blur > 0) ||
85
+ !!recipe.grayscale ||
86
+ !!recipe.sepia ||
87
+ !!recipe.invert ||
88
+ (recipe.regions?.length ?? 0) > 0 ||
89
+ (recipe.annotations?.length ?? 0) > 0
90
+ );
91
+ }
92
+
93
+ /** Build a composite layer that blurs or pixelates one region of the oriented image. */
94
+ async function buildRegionComposite(
95
+ orientedBuf: Buffer,
96
+ region: ImageEditRegion,
97
+ imgWidth: number,
98
+ imgHeight: number
99
+ ): Promise<{ input: Buffer; left: number; top: number }> {
100
+ const r = boundCrop(
101
+ { left: region.left, top: region.top, width: region.width, height: region.height },
102
+ imgWidth,
103
+ imgHeight
104
+ );
105
+ const strength = Math.max(1, Math.min(100, region.strength || 1));
106
+ let img = sharp(orientedBuf).extract(r);
107
+ if (region.type === 'blur') {
108
+ img = img.blur(Math.max(0.3, strength / 3));
109
+ } else {
110
+ // Mosaic: downscale with nearest-neighbour, then scale back up.
111
+ const factor = Math.max(2, Math.round(strength / 3));
112
+ const dw = Math.max(1, Math.round(r.width / factor));
113
+ const dh = Math.max(1, Math.round(r.height / factor));
114
+ img = img
115
+ .resize(dw, dh, { kernel: 'nearest' })
116
+ .resize(r.width, r.height, { kernel: 'nearest' });
117
+ }
118
+ return { input: await img.png().toBuffer(), left: r.left, top: r.top };
119
+ }
120
+
121
+ /** Render freehand strokes to an SVG overlay sized to the oriented image. */
122
+ function buildAnnotationSvg(strokes: ImageEditStroke[], width: number, height: number): string {
123
+ const lines = strokes
124
+ .map((s) => {
125
+ const color = /^#[0-9a-fA-F]{3,8}$/.test(s.color) ? s.color : '#ef4444';
126
+ const w = Math.max(1, Math.min(400, s.size || 4));
127
+ const opacity = Math.max(0, Math.min(1, s.opacity ?? 1));
128
+ const pts = s.points
129
+ .filter((p) => Number.isFinite(p.x) && Number.isFinite(p.y))
130
+ .map((p) => `${Math.round(p.x)},${Math.round(p.y)}`)
131
+ .join(' ');
132
+ if (!pts) return '';
133
+ return `<polyline points="${pts}" fill="none" stroke="${color}" stroke-width="${w}" stroke-opacity="${opacity}" stroke-linecap="round" stroke-linejoin="round"/>`;
134
+ })
135
+ .join('');
136
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}">${lines}</svg>`;
137
+ }
138
+
139
+ /**
140
+ * Encode the pipeline into the requested output format.
141
+ *
142
+ * `compress` opt-in (per format):
143
+ * - off → preserve quality: lossless for PNG/WebP, high quality otherwise. The
144
+ * caller copies the original byte-for-byte when there are no other edits, so
145
+ * this path only runs when geometry/color/format actually changed.
146
+ * - on → efficient codecs that shrink files at visually-equivalent quality:
147
+ * mozjpeg for JPEG, palette quantization for PNG (in encodeToBuffer),
148
+ * efficient lossy WebP/AVIF.
149
+ */
150
+ function encode(pipeline: Sharp, output: ImageEditRecipe['output'], fast = false): Sharp {
151
+ const compress = output.compress ?? false;
152
+ const quality = output.quality ?? 80;
153
+ switch (output.format) {
154
+ case 'png':
155
+ // Lossy PNG (palette quantization) is handled in encodeToBuffer; here
156
+ // we always produce the lossless variant. `fast` trades a little size
157
+ // accuracy for speed (used by the live estimate on large images).
158
+ return pipeline.png({ compressionLevel: fast ? 6 : 9, effort: fast ? 1 : 10 });
159
+ case 'jpeg':
160
+ // mozjpeg = trellis quantization + optimized Huffman + progressive.
161
+ return pipeline.jpeg({ quality: compress ? quality : 95, mozjpeg: true });
162
+ case 'webp':
163
+ return output.lossless || !compress
164
+ ? pipeline.webp({ lossless: true, effort: fast ? 0 : 6 })
165
+ : pipeline.webp({ quality, effort: fast ? 0 : 6, smartSubsample: true });
166
+ case 'gif':
167
+ return pipeline.gif({ dither: 1 });
168
+ case 'avif':
169
+ // Off = preserve quality (near-lossless); on = the requested quality.
170
+ // Keep the two clearly apart so toggling compression changes the size.
171
+ // AVIF effort is the slowest knob — drop it hard for the estimate.
172
+ return pipeline.avif({ quality: compress ? (output.quality ?? 80) : 92, effort: fast ? 0 : 4 });
173
+ default: {
174
+ // Exhaustiveness guard — unreachable for valid recipes.
175
+ const never: never = output.format;
176
+ throw new Error(`Unsupported output format: ${String(never)}`);
177
+ }
178
+ }
179
+ }
180
+
181
+ /**
182
+ * Apply a recipe to the image at `sourcePath` and return the encoded result.
183
+ * Throws if the source is not a decodable image or the output exceeds the
184
+ * configured file-size limit.
185
+ */
186
+ export async function processImageEdit(
187
+ sourcePath: string,
188
+ recipe: ImageEditRecipe,
189
+ fast = false
190
+ ): Promise<ProcessedImage> {
191
+ const srcMeta = await sharp(sourcePath, { animated: true }).metadata();
192
+ if (!srcMeta.width || !srcMeta.height) {
193
+ throw new Error('Source file is not a readable image');
194
+ }
195
+
196
+ // Nothing to do: not compressing, no edits, and the format is unchanged →
197
+ // return the original bytes verbatim so an untouched file stays identical.
198
+ const compress = recipe.output.compress ?? false;
199
+ if (!compress && !hasEdits(recipe) && srcMeta.format === recipe.output.format) {
200
+ const data = Buffer.from(await Bun.file(sourcePath).arrayBuffer());
201
+ validateFileSize(data.length);
202
+ return {
203
+ data,
204
+ format: srcMeta.format ?? recipe.output.format,
205
+ width: srcMeta.width,
206
+ height: srcMeta.height,
207
+ size: data.length
208
+ };
209
+ }
210
+
211
+ const animated = (srcMeta.pages ?? 1) > 1;
212
+ const rotate = recipe.rotate ?? 0;
213
+
214
+ let pipeline: Sharp;
215
+
216
+ if (animated) {
217
+ // Single pass keeps every frame. sharp applies extract/resize per frame.
218
+ let p = sharp(sourcePath, { animated: true });
219
+ if (rotate) p = p.rotate(rotate);
220
+ if (recipe.flipV) p = p.flip();
221
+ if (recipe.flipH) p = p.flop();
222
+ if (recipe.crop) {
223
+ p = p.extract(boundCrop(recipe.crop, srcMeta.width, srcMeta.height));
224
+ }
225
+ if (recipe.resize) {
226
+ p = p.resize(Math.round(recipe.resize.width), Math.round(recipe.resize.height), { fit: 'fill' });
227
+ }
228
+ pipeline = applyColor(p, recipe);
229
+ } else {
230
+ // The browser decodes images with EXIF orientation applied, so the editor's
231
+ // coordinates live in that space. EXIF-oriented dimensions are derived from
232
+ // metadata (orientation 5–8 swap W/H) so the common no-rotation path never
233
+ // has to fully decode a large image just to estimate its size.
234
+ const exifSwap = (srcMeta.orientation ?? 1) >= 5;
235
+ const baseW = exifSwap ? srcMeta.height : srcMeta.width;
236
+ const baseH = exifSwap ? srcMeta.width : srcMeta.height;
237
+
238
+ const quarterTurn = rotate === 90 || rotate === 270;
239
+ const orientedWidth = quarterTurn ? baseH : baseW;
240
+ const orientedHeight = quarterTurn ? baseW : baseH;
241
+
242
+ const regions = recipe.regions ?? [];
243
+ const annotations = recipe.annotations ?? [];
244
+
245
+ // Decode the EXIF-auto-oriented source into a raw buffer. Only used when a
246
+ // rotation/flip must be baked (so crop maps after rotation) or overlays are
247
+ // composited — the plain path below stays lazy.
248
+ const decodeOrientedRaw = async () => {
249
+ const { data, info } = await sharp(sourcePath)
250
+ .rotate()
251
+ .ensureAlpha()
252
+ .raw()
253
+ .toBuffer({ resolveWithObject: true });
254
+ return sharp(data, { raw: { width: info.width, height: info.height, channels: info.channels } });
255
+ };
256
+
257
+ if (regions.length > 0 || annotations.length > 0) {
258
+ // Bake orientation + color first, then composite blur/pixelate regions
259
+ // and freehand strokes in oriented space, then crop/resize/encode.
260
+ let oriented = (await decodeOrientedRaw()).rotate(rotate);
261
+ if (recipe.flipV) oriented = oriented.flip();
262
+ if (recipe.flipH) oriented = oriented.flop();
263
+ oriented = applyColor(oriented, recipe);
264
+ const orientedBuf = await oriented.png().toBuffer();
265
+
266
+ // Composite layers must fit the *actual* baked buffer, which can differ
267
+ // from the metadata-derived oriented size by a sub-pixel after EXIF
268
+ // auto-orient + rotate. Measure the real dimensions and size every
269
+ // layer against them, or sharp rejects them ("same dimensions or smaller").
270
+ const bakedMeta = await sharp(orientedBuf).metadata();
271
+ const ow = bakedMeta.width ?? orientedWidth;
272
+ const oh = bakedMeta.height ?? orientedHeight;
273
+
274
+ const composites: { input: Buffer; left: number; top: number }[] = [];
275
+ for (const region of regions) {
276
+ composites.push(await buildRegionComposite(orientedBuf, region, ow, oh));
277
+ }
278
+ if (annotations.length > 0) {
279
+ // Rasterize the overlay to an exact-size PNG first. Compositing a raw
280
+ // SVG buffer can be rejected ("same dimensions or smaller") when
281
+ // librsvg rounds the raster up by a sub-pixel versus the base.
282
+ const svg = buildAnnotationSvg(annotations, ow, oh);
283
+ const svgPng = await sharp(Buffer.from(svg))
284
+ .resize(ow, oh, { fit: 'fill' })
285
+ .png()
286
+ .toBuffer();
287
+ composites.push({ input: svgPng, left: 0, top: 0 });
288
+ }
289
+
290
+ // Flatten the composites into the base BEFORE cropping/resizing. sharp
291
+ // orders pipeline ops internally (extract/resize run before composite),
292
+ // so chaining .composite().extract() on one pipeline would crop the base
293
+ // first and then reject the full-size overlay. Baking to a buffer pins
294
+ // the overlay to the full oriented frame it was authored against.
295
+ const compositedBuf =
296
+ composites.length > 0
297
+ ? await sharp(orientedBuf).composite(composites).png().toBuffer()
298
+ : orientedBuf;
299
+
300
+ let p = sharp(compositedBuf);
301
+ if (recipe.crop) {
302
+ p = p.extract(boundCrop(recipe.crop, ow, oh));
303
+ }
304
+ if (recipe.resize) {
305
+ p = p.resize(Math.round(recipe.resize.width), Math.round(recipe.resize.height), { fit: 'fill' });
306
+ }
307
+ // Color already baked above.
308
+ pipeline = p;
309
+ } else if (rotate || recipe.flipH || recipe.flipV) {
310
+ // Bake EXIF + user orientation into a raw buffer so the crop coordinates
311
+ // (expressed against the oriented preview) map exactly — sharp's single
312
+ // pipeline does not honor rotate-before-extract call order.
313
+ let pre = (await decodeOrientedRaw()).rotate(rotate);
314
+ if (recipe.flipV) pre = pre.flip();
315
+ if (recipe.flipH) pre = pre.flop();
316
+ const { data, info } = await pre.raw().toBuffer({ resolveWithObject: true });
317
+ let p = sharp(data, { raw: { width: info.width, height: info.height, channels: info.channels } });
318
+ if (recipe.crop) {
319
+ p = p.extract(boundCrop(recipe.crop, orientedWidth, orientedHeight));
320
+ }
321
+ if (recipe.resize) {
322
+ p = p.resize(Math.round(recipe.resize.width), Math.round(recipe.resize.height), { fit: 'fill' });
323
+ }
324
+ pipeline = applyColor(p, recipe);
325
+ } else {
326
+ // No rotation/flip: stay lazy. `.rotate()` auto-orients via EXIF before
327
+ // extract, so crop coordinates still map to the displayed image.
328
+ let p = sharp(sourcePath).rotate();
329
+ if (recipe.crop) {
330
+ p = p.extract(boundCrop(recipe.crop, orientedWidth, orientedHeight));
331
+ }
332
+ if (recipe.resize) {
333
+ p = p.resize(Math.round(recipe.resize.width), Math.round(recipe.resize.height), { fit: 'fill' });
334
+ }
335
+ pipeline = applyColor(p, recipe);
336
+ }
337
+ }
338
+
339
+ const { data, info } = await encodeToBuffer(pipeline, recipe.output, fast);
340
+
341
+ // Guard against producing an output larger than the admin file-size limit.
342
+ validateFileSize(data.length);
343
+
344
+ return {
345
+ data,
346
+ format: info.format,
347
+ width: info.width,
348
+ height: info.height,
349
+ size: data.length
350
+ };
351
+ }
352
+
353
+ /**
354
+ * Encode to a Buffer. For lossy PNG we render both palette-quantized and
355
+ * lossless variants and keep the smaller one — palette quantization shrinks
356
+ * photographic PNGs dramatically but can *grow* smooth/continuous-tone images,
357
+ * so "compress" must never increase the size.
358
+ */
359
+ async function encodeToBuffer(
360
+ pipeline: Sharp,
361
+ output: ImageEditRecipe['output'],
362
+ fast = false
363
+ ): Promise<{ data: Buffer; info: { format: string; width: number; height: number } }> {
364
+ if (output.format === 'png' && (output.compress ?? false) && !output.lossless) {
365
+ const quality = output.quality ?? 80;
366
+ // Estimate path: a single fast palette encode instead of the dual
367
+ // palette/lossless comparison (which is too slow on large images).
368
+ if (fast) {
369
+ return pipeline
370
+ .png({ palette: true, quality, dither: 1, effort: 1, compressionLevel: 6 })
371
+ .toBuffer({ resolveWithObject: true });
372
+ }
373
+ const [palette, lossless] = await Promise.all([
374
+ pipeline
375
+ .clone()
376
+ .png({ palette: true, quality, dither: 1, effort: 10, compressionLevel: 9 })
377
+ .toBuffer({ resolveWithObject: true }),
378
+ pipeline.clone().png({ compressionLevel: 9, effort: 10 }).toBuffer({ resolveWithObject: true })
379
+ ]);
380
+ return palette.data.length <= lossless.data.length ? palette : lossless;
381
+ }
382
+ return encode(pipeline, output, fast).toBuffer({ resolveWithObject: true });
383
+ }
384
+
385
+ /** Clamp a crop rectangle so it always sits within the image bounds. */
386
+ function boundCrop(
387
+ crop: NonNullable<ImageEditRecipe['crop']>,
388
+ imgWidth: number,
389
+ imgHeight: number
390
+ ): { left: number; top: number; width: number; height: number } {
391
+ const left = clampInt(crop.left, 0, Math.max(0, imgWidth - 1));
392
+ const top = clampInt(crop.top, 0, Math.max(0, imgHeight - 1));
393
+ const width = clampInt(crop.width, 1, imgWidth - left);
394
+ const height = clampInt(crop.height, 1, imgHeight - top);
395
+ return { left, top, width, height };
396
+ }
@@ -4,6 +4,8 @@
4
4
  */
5
5
 
6
6
  import { execGit, isGitRepo, getGitRoot } from './git-executor';
7
+ import { resolveBinary } from '../utils/cli';
8
+ import { getCleanSpawnEnv } from '../utils/env';
7
9
  import {
8
10
  parseStatus,
9
11
  parseBranches,
@@ -378,9 +380,11 @@ export class GitService {
378
380
  return result.stderr || result.stdout; // git fetch outputs to stderr
379
381
  }
380
382
 
381
- async pull(cwd: string, remote = 'origin', branch?: string): Promise<{ success: boolean; message: string }> {
383
+ async pull(cwd: string, remote = 'origin', branch?: string, rebase = false): Promise<{ success: boolean; message: string }> {
382
384
  assertSafeGitRemoteName(remote);
383
- const args = ['pull', remote];
385
+ const args = ['pull'];
386
+ if (rebase) args.push('--rebase');
387
+ args.push(remote);
384
388
  if (branch) {
385
389
  assertSafeGitRevish(branch, 'pull branch');
386
390
  args.push(branch);
@@ -409,6 +413,49 @@ export class GitService {
409
413
  };
410
414
  }
411
415
 
416
+ /**
417
+ * Advanced push variants surfaced in the "More" menu:
418
+ * - `with-tags` → push branch + reachable annotated tags (--follow-tags)
419
+ * - `all-tags` → push all local tags (--tags), no branch
420
+ * - `force-lease` → safe force push (--force-with-lease)
421
+ * - `force` → unconditional force push (--force)
422
+ */
423
+ async pushAdvanced(
424
+ cwd: string,
425
+ mode: 'with-tags' | 'all-tags' | 'force-lease' | 'force',
426
+ remote = 'origin',
427
+ branch?: string
428
+ ): Promise<{ success: boolean; message: string }> {
429
+ assertSafeGitRemoteName(remote);
430
+ const args = ['push', remote];
431
+ if (mode === 'all-tags') {
432
+ args.push('--tags');
433
+ } else {
434
+ if (branch) {
435
+ assertSafeGitRevish(branch, 'push branch');
436
+ args.push(branch);
437
+ }
438
+ if (mode === 'with-tags') args.push('--follow-tags');
439
+ else if (mode === 'force-lease') args.push('--force-with-lease');
440
+ else if (mode === 'force') args.push('--force');
441
+ args.push('-u');
442
+ }
443
+ const result = await execGit(args, cwd, 60000);
444
+ return {
445
+ success: result.exitCode === 0,
446
+ message: result.exitCode === 0 ? (result.stderr || result.stdout) : result.stderr
447
+ };
448
+ }
449
+
450
+ /** Fetch every configured remote and prune deleted remote-tracking refs. */
451
+ async fetchAll(cwd: string): Promise<string> {
452
+ const result = await execGit(['fetch', '--all', '--prune', '--tags'], cwd, 60000);
453
+ if (result.exitCode !== 0) {
454
+ throw new Error(`git fetch --all failed: ${result.stderr}`);
455
+ }
456
+ return result.stderr || result.stdout;
457
+ }
458
+
412
459
  async addRemote(cwd: string, name: string, url: string): Promise<void> {
413
460
  assertSafeGitRemoteName(name);
414
461
  assertSafeGitRemoteUrl(url);
@@ -627,6 +674,92 @@ export class GitService {
627
674
  throw new Error(`git reset --merge failed: ${reset.stderr}`);
628
675
  }
629
676
  }
677
+
678
+ // ============================================
679
+ // History rewrite / undo
680
+ // ============================================
681
+
682
+ /**
683
+ * Undo the last commit by moving HEAD back one commit.
684
+ * - `soft` keeps the changes staged
685
+ * - `mixed` keeps the changes in the working tree (unstaged)
686
+ * - `hard` discards the changes entirely (destructive)
687
+ */
688
+ async undoLastCommit(cwd: string, mode: 'soft' | 'mixed' | 'hard'): Promise<void> {
689
+ const flag = mode === 'soft' ? '--soft' : mode === 'hard' ? '--hard' : '--mixed';
690
+ const result = await execGit(['reset', flag, 'HEAD~1'], cwd);
691
+ if (result.exitCode !== 0) {
692
+ throw new Error(`git reset ${flag} failed: ${result.stderr}`);
693
+ }
694
+ }
695
+
696
+ /** Create a new commit that reverses a previous one (default: HEAD). */
697
+ async revertCommit(cwd: string, ref = 'HEAD'): Promise<{ success: boolean; message: string }> {
698
+ assertSafeGitRevish(ref, 'revert ref');
699
+ const result = await execGit(['revert', '--no-edit', ref], cwd);
700
+ return {
701
+ success: result.exitCode === 0,
702
+ message: result.exitCode === 0 ? (result.stdout || result.stderr) : result.stderr
703
+ };
704
+ }
705
+
706
+ // ============================================
707
+ // Maintenance
708
+ // ============================================
709
+
710
+ /** Remove untracked files and directories (`git clean -fd`). */
711
+ async cleanUntracked(cwd: string): Promise<string> {
712
+ const result = await execGit(['clean', '-fd'], cwd);
713
+ if (result.exitCode !== 0) {
714
+ throw new Error(`git clean failed: ${result.stderr}`);
715
+ }
716
+ return result.stdout.trim();
717
+ }
718
+
719
+ /** Run garbage collection to optimize the repository. */
720
+ async optimize(cwd: string): Promise<string> {
721
+ const result = await execGit(['gc'], cwd, 180000);
722
+ if (result.exitCode !== 0) {
723
+ throw new Error(`git gc failed: ${result.stderr}`);
724
+ }
725
+ return (result.stderr || result.stdout).trim() || 'Repository optimized';
726
+ }
727
+
728
+ // ============================================
729
+ // npm version
730
+ // ============================================
731
+
732
+ /**
733
+ * Bump the package version with `npm version <patch|minor|major>`. In a git
734
+ * repo npm creates the version-bump commit and tag automatically. Requires a
735
+ * clean working tree (npm refuses otherwise) — that error is surfaced verbatim.
736
+ */
737
+ async npmVersion(
738
+ cwd: string,
739
+ bump: 'patch' | 'minor' | 'major'
740
+ ): Promise<{ success: boolean; version: string; message: string }> {
741
+ const npmPath = resolveBinary('npm');
742
+ if (!npmPath) {
743
+ throw new Error('npm binary not found on PATH');
744
+ }
745
+ const proc = Bun.spawn([npmPath, 'version', bump, '-m', 'chore(release): v%s'], {
746
+ cwd,
747
+ stdout: 'pipe',
748
+ stderr: 'pipe',
749
+ env: { ...getCleanSpawnEnv() }
750
+ });
751
+ const [stdout, stderr] = await Promise.all([
752
+ new Response(proc.stdout).text(),
753
+ new Response(proc.stderr).text()
754
+ ]);
755
+ const exitCode = await proc.exited;
756
+ if (exitCode !== 0) {
757
+ return { success: false, version: '', message: (stderr || stdout).trim() };
758
+ }
759
+ // npm prints the new version (e.g. "v1.2.3") on stdout.
760
+ const version = stdout.trim().split('\n').pop()?.trim() || '';
761
+ return { success: true, version, message: version };
762
+ }
630
763
  }
631
764
 
632
765
  // Singleton
@@ -669,26 +669,29 @@ class BrowserPreviewServiceManager {
669
669
  ws.emit.project(projectId, 'preview:browser-navigation-spa', data);
670
670
  });
671
671
 
672
- // Forward tab events
672
+ // Forward tab events. Each carries projectId so the frontend can drop
673
+ // events for a project it has since switched away from — without it, a
674
+ // background stream (or a late event) could create/mutate tabs in the
675
+ // project the user is now viewing.
673
676
  service.on('preview:browser-tab-opened', (data) => {
674
677
  debug.log('preview', `🚀 Forwarding preview:browser-tab-opened to project ${projectId}:`, data);
675
- ws.emit.project(projectId, 'preview:browser-tab-opened', data);
678
+ ws.emit.project(projectId, 'preview:browser-tab-opened', { ...data, projectId });
676
679
  });
677
680
 
678
681
  service.on('preview:browser-tab-closed', (data) => {
679
- ws.emit.project(projectId, 'preview:browser-tab-closed', data);
682
+ ws.emit.project(projectId, 'preview:browser-tab-closed', { ...data, projectId });
680
683
  });
681
684
 
682
685
  service.on('preview:browser-tab-switched', (data) => {
683
- ws.emit.project(projectId, 'preview:browser-tab-switched', data);
686
+ ws.emit.project(projectId, 'preview:browser-tab-switched', { ...data, projectId });
684
687
  });
685
688
 
686
689
  service.on('preview:browser-tab-navigated', (data) => {
687
- ws.emit.project(projectId, 'preview:browser-tab-navigated', data);
690
+ ws.emit.project(projectId, 'preview:browser-tab-navigated', { ...data, projectId });
688
691
  });
689
692
 
690
693
  service.on('preview:browser-viewport-changed', (data) => {
691
- ws.emit.project(projectId, 'preview:browser-viewport-changed', data);
694
+ ws.emit.project(projectId, 'preview:browser-viewport-changed', { ...data, projectId });
692
695
  });
693
696
 
694
697
  // Forward console events
@@ -747,7 +747,9 @@ class WSServer {
747
747
 
748
748
  const room = this.projectRooms.get(projectId);
749
749
  if (!room || room.size === 0) {
750
- debug.warn('websocket', `No connections in project room: ${projectId} for event: ${String(event)}`);
750
+ // Expected/benign: e.g. a background terminal in a project the client
751
+ // has switched away from keeps emitting output to an empty room.
752
+ debug.log('websocket', `No connections in project room: ${projectId} for event: ${String(event)}`);
751
753
  return;
752
754
  }
753
755