Skip to content

Commit bc2aa9c

Browse files
committed
Sync 17 public-facing changes
- docs(slicer): drop a private-doc pointer from the preset-record guard - fix(slicer,editor): close the review findings on the machine-override work - fix(slicer): report the print's prepare phase, not the CLI's own wall clock - build(dev): stop a dev server outliving its watcher, and report it when one does - refactor(slicer): give the parallel preset records one owner, and guard it - fix(editor): make resetting a printer override actually reach the file - fix(slicer): own the changed-from-system record in one place, indexed as the engine does - fix(slicer): make a project's machine override survive save and reopen - feat(slicer): pick a printer preset, and modify it for one project - refactor(web): shorten the plate section Add buttons to the verb - fix(web): restore an abandoned preset search instead of leaving it in the box - refactor(web): shrink the Bambu Cloud sync notice to a badged icon control - fix(editor): carry helper volume types across a replace, matched by name - fix(editor): resolve a part's material through its inheritance rule when recolouring - fix(editor,print): five reported bugs in replace, resume, skip and part deletion - test(repo): fail the build on a newly added em dash - chore(slicer): move to BambuStudio 2.8.2.61 Source-Revision: 45cdd119dd3bcd65c8b9c886a41b92293464d21a
1 parent e22496d commit bc2aa9c

101 files changed

Lines changed: 5584 additions & 610 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/api/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
"scripts": {
1212
"build": "tsc -p tsconfig.json",
1313
"predev": "npm run build --workspace @printstream/shared",
14-
"dev": "tsx watch --include \"../../packages/shared/dist/**\" --include \"../../packages/bridge-runtime/dist/**\" src/server.ts",
14+
"dev": "NODE_OPTIONS=\"--require ../../scripts/dev/exit-with-parent.cjs\" tsx watch --include \"../../packages/shared/dist/**\" --include \"../../packages/bridge-runtime/dist/**\" src/server.ts",
1515
"start": "node dist/server.js",
1616
"typecheck": "tsc --noEmit -p tsconfig.json",
1717
"prisma:db:push": "prisma db push",

‎apps/api/src/index.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import { ensureBuiltInPlatformAuthGroups } from './lib/default-auth-groups.js'
3535
import { ensureDefaultWorkspace } from './lib/default-workspace.js'
3636
import { rootPrisma } from './lib/prisma.js'
3737
import { ensureManagedBridgeToken, isManagedBridgeMode } from './lib/managed-bridge.js'
38+
import { startDevSourceStalenessWatch } from './lib/dev-source-staleness.js'
3839

3940
const httpServer = createServer(app)
4041
attachWebSocketServer(httpServer)
@@ -77,6 +78,9 @@ void finalizeApp()
7778
})
7879
httpServer.listen(env.API_PORT, () => {
7980
console.log(`printstream API listening on http://localhost:${env.API_PORT}`)
81+
// Dev only, and deliberately first: it reports that this process is serving code older than
82+
// the repo, which is a condition that makes every observation after it untrustworthy.
83+
startDevSourceStalenessWatch()
8084
void (async () => {
8185
try {
8286
// Opt-in (METRICS_ENABLED); a no-op otherwise. Gauges read live counts
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
/**
2+
* The staleness detector has to be right in BOTH directions, and each wrong answer is its own
3+
* failure. A missed staleness returns this API to the condition the module exists to end (hours of
4+
* debugging correct code). A false alarm is worse than useless: a warning that cries wolf gets
5+
* ignored, and then the real one is ignored too.
6+
*
7+
* The roots test is the one that will actually catch a regression. The watch list is a MIRROR of
8+
* what `tsx watch` is told to watch, kept in two files that nothing links, so it goes out of step
9+
* the first time someone adds an `--include` to the dev script.
10+
*/
11+
import assert from 'node:assert/strict'
12+
import { mkdtemp, mkdir, readFile, rm, utimes, writeFile } from 'node:fs/promises'
13+
import { tmpdir } from 'node:os'
14+
import path from 'node:path'
15+
import { fileURLToPath } from 'node:url'
16+
import { test } from 'node:test'
17+
import { WATCH_ROOTS, evaluateSourceStaleness } from './dev-source-staleness.js'
18+
19+
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../..')
20+
21+
/**
22+
* A tree whose files all predate `baseMs`, so a test can then age ONE file forward. Removed when the
23+
* test finishes: `npm run validate` is the repo's inner loop, and leaked trees accumulate in tmp.
24+
*/
25+
async function makeTree(t: { after: (fn: () => void | Promise<void>) => void }): Promise<{ root: string; baseMs: number }> {
26+
const root = await mkdtemp(path.join(tmpdir(), 'staleness-'))
27+
t.after(async () => { await rm(root, { recursive: true, force: true }) })
28+
const baseMs = Date.now() - 60_000
29+
await mkdir(path.join(root, 'apps/api/src/lib'), { recursive: true })
30+
await mkdir(path.join(root, 'packages/shared/dist'), { recursive: true })
31+
await mkdir(path.join(root, 'apps/api/src/node_modules/junk'), { recursive: true })
32+
const old = new Date(baseMs - 60_000)
33+
for (const relative of ['apps/api/src/index.ts', 'apps/api/src/lib/thing.ts', 'packages/shared/dist/index.js']) {
34+
await writeFile(path.join(root, relative), '// x')
35+
await utimes(path.join(root, relative), old, old)
36+
}
37+
return { root, baseMs }
38+
}
39+
40+
const ROOTS = ['apps/api/src', 'packages/shared/dist'] as const
41+
42+
test('a tree older than the process is not stale', async (t) => {
43+
const { root, baseMs } = await makeTree(t)
44+
const result = await evaluateSourceStaleness({ roots: ROOTS, startedAtMs: baseMs, root })
45+
assert.equal(result.stale, false)
46+
assert.ok(result.lastCheckedAt, 'a completed scan always reports when it ran')
47+
})
48+
49+
test('one file newer than the process makes it stale, and names that file', async (t) => {
50+
const { root, baseMs } = await makeTree(t)
51+
const edited = new Date(baseMs + 30_000)
52+
await utimes(path.join(root, 'apps/api/src/lib/thing.ts'), edited, edited)
53+
54+
const result = await evaluateSourceStaleness({ roots: ROOTS, startedAtMs: baseMs, root })
55+
assert.equal(result.stale, true)
56+
// Naming the file is most of the value: it turns "something is stale" into "this edit is the one
57+
// you are not running", which is the sentence that ends the wrong-headed debugging session.
58+
assert.equal(result.newestPath, 'apps/api/src/lib/thing.ts')
59+
})
60+
61+
test('a compiled package rebuilt after boot counts, not just this app\'s own source', async (t) => {
62+
// The second shape of the bug: the API's watcher is fine but `packages/shared` was rebuilt and
63+
// never picked up, so the API runs against a dist it has not loaded.
64+
const { root, baseMs } = await makeTree(t)
65+
const rebuilt = new Date(baseMs + 30_000)
66+
await utimes(path.join(root, 'packages/shared/dist/index.js'), rebuilt, rebuilt)
67+
68+
const result = await evaluateSourceStaleness({ roots: ROOTS, startedAtMs: baseMs, root })
69+
assert.equal(result.stale, true)
70+
assert.equal(result.newestPath, 'packages/shared/dist/index.js')
71+
})
72+
73+
test('a colocated test file is ignored, so editing one cannot raise a false alarm', async (t) => {
74+
// `apps/api/src` holds ~270 `*.test.ts`, none of them imported by `server.ts`, so `tsx watch`
75+
// never reloads for one. Counting them latched "RUNNING STALE CODE" true for the life of the
76+
// process the first time anyone edited a test -- which this repo asks for with every change. A
77+
// warning that is wrong most of the time is how a warning stops being read at all.
78+
const { root, baseMs } = await makeTree(t)
79+
const edited = new Date(baseMs + 30_000)
80+
const testFile = path.join(root, 'apps/api/src/lib/thing.test.ts')
81+
await writeFile(testFile, '// a regression test')
82+
await utimes(testFile, edited, edited)
83+
84+
const result = await evaluateSourceStaleness({ roots: ROOTS, startedAtMs: baseMs, root })
85+
assert.equal(result.stale, false)
86+
})
87+
88+
test('node_modules is ignored, so an install cannot raise a false alarm', async (t) => {
89+
// `npm install` touches thousands of files under a watched tree and reloads nothing. Counting
90+
// them would report staleness on every install, which is exactly how a warning stops being read.
91+
const { root, baseMs } = await makeTree(t)
92+
const installed = new Date(baseMs + 30_000)
93+
const junk = path.join(root, 'apps/api/src/node_modules/junk/index.js')
94+
await writeFile(junk, '// installed')
95+
await utimes(junk, installed, installed)
96+
97+
const result = await evaluateSourceStaleness({ roots: ROOTS, startedAtMs: baseMs, root })
98+
assert.equal(result.stale, false)
99+
})
100+
101+
test('missing roots are skipped rather than failing the scan', async (t) => {
102+
// A fresh checkout has no `dist` yet. Refusing to answer would turn "not built" into "not checked".
103+
const { root, baseMs } = await makeTree(t)
104+
const result = await evaluateSourceStaleness({ roots: [...ROOTS, 'packages/nope/dist'], startedAtMs: baseMs, root })
105+
assert.equal(result.stale, false)
106+
assert.ok(result.lastCheckedAt)
107+
})
108+
109+
test('WATCH_ROOTS covers everything the dev script tells tsx watch to watch', async () => {
110+
// The two lists live in different files with no link between them, so this is the regression that
111+
// will actually happen: someone adds an `--include` and the detector silently stops seeing it.
112+
const packageJson = JSON.parse(await readFile(path.join(repoRoot, 'apps/api/package.json'), 'utf8')) as {
113+
scripts: Record<string, string>
114+
}
115+
const dev = packageJson.scripts.dev ?? ''
116+
117+
const included = [...dev.matchAll(/--include\s+"?([^"\s]+)"?/g)]
118+
.map((match) => match[1]!)
119+
// `../../packages/shared/dist/**` is stated relative to apps/api; the detector's roots are
120+
// stated relative to the repo, so compare on the repo-relative form.
121+
.map((glob) => path.normalize(path.join('apps/api', glob)).replace(/[\\/]\*+$/, ''))
122+
123+
for (const root of included) {
124+
assert.ok(WATCH_ROOTS.includes(root), `the dev script watches ${root} but WATCH_ROOTS does not, so staleness there is invisible`)
125+
}
126+
// The entry tree is watched implicitly by tsx (it is where the entry lives), never via --include.
127+
assert.ok(WATCH_ROOTS.includes('apps/api/src'), 'the API\'s own source tree must be watched')
128+
})
Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
/**
2+
* DEV ONLY. Reports when the source on disk is NEWER than the running process, i.e. when this API
3+
* is serving code that no longer matches the repo.
4+
*
5+
* Owns one question and answers it honestly: "is what I am running still what is written down?" It
6+
* never restarts anything and never reloads anything. A dev server that healed itself behind the
7+
* user's back would hide the very condition this exists to make visible.
8+
*
9+
* WHY: the failure it reports is silent by construction. `tsx watch` runs the server as a separate
10+
* child, so a dead watcher leaves a healthy-looking process serving its boot-time code forever, and
11+
* a `packages/*` build watcher that stops emitting does the same thing one layer up. Nothing logs
12+
* either. The symptom reaching a human is "my edit had no effect", which reads as a bug in the edit,
13+
* so the reasonable next move is to go debugging code that is already correct. That happened on
14+
* 2026-08-30: the API served 9-minute-old code for 14 hours across four rounds of "still broken".
15+
*
16+
* Its counterpart `scripts/dev/exit-with-parent.cjs` PREVENTS the common cause (an orphaned server
17+
* now dies with its watcher). This covers what prevention cannot see: a watcher that is alive but
18+
* wedged, and a compiled package `dist` that was never rebuilt. Both leave a correctly-parented
19+
* process running stale code.
20+
*
21+
* Surfaced two ways, because each catches a different reader: a loud `console.error` for anyone
22+
* tailing the dev log, and a field on `GET /api/health`'s dev-only `runtime` block for anyone (or
23+
* any agent) probing the API after something looks wrong.
24+
*/
25+
import { readdir, stat } from 'node:fs/promises'
26+
import path from 'node:path'
27+
import { fileURLToPath } from 'node:url'
28+
import { env } from './env.js'
29+
30+
/**
31+
* The trees whose freshness decides the answer.
32+
*
33+
* MUST mirror what the API's `dev` script tells `tsx watch` to watch (`apps/api/package.json`: its
34+
* entry tree plus the two `--include` globs). A root watched there but missing here is a staleness
35+
* this cannot see; a root here but not there would report a change that was never going to reload
36+
* anything, which is a false alarm and worse than silence.
37+
*/
38+
export const WATCH_ROOTS = ['apps/api/src', 'packages/shared/dist', 'packages/bridge-runtime/dist']
39+
40+
/**
41+
* Files inside a watched root that the SERVER never imports, and which therefore never reload it.
42+
*
43+
* Colocated tests are the big one: `apps/api/src` holds ~270 `*.test.ts`, none of them reachable
44+
* from `server.ts`, and this repo asks for a regression test with every change. Counting them meant
45+
* editing any test latched `stale` true for the life of the process and repeated the alarm every
46+
* five minutes -- a warning that is wrong most of the time, which is how a warning stops being read
47+
* at all. This module's own contract calls that outcome worse than silence.
48+
*/
49+
const IGNORED_SUFFIXES = ['.test.ts', '.test.tsx']
50+
const IGNORED_DIRECTORIES = new Set(['test-utils', '__fixtures__'])
51+
52+
const SCAN_INTERVAL_MS = 30_000
53+
/** Re-log while still stale: the first line scrolls away, and this condition lasts hours. */
54+
const RELOG_INTERVAL_MS = 5 * 60_000
55+
56+
export interface DevSourceStaleness {
57+
/** True when a watched file is newer than this process. */
58+
stale: boolean
59+
/** The newest watched file, repo-relative. Null before the first scan completes. */
60+
newestPath: string | null
61+
newestModifiedAt: string | null
62+
lastCheckedAt: string | null
63+
}
64+
65+
let current: DevSourceStaleness = { stale: false, newestPath: null, newestModifiedAt: null, lastCheckedAt: null }
66+
let lastLoggedAt = 0
67+
68+
/** Process start, as a wall-clock millisecond stamp: what every mtime is measured against. */
69+
const processStartedAtMs = Date.now() - Math.round(process.uptime() * 1000)
70+
71+
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../..')
72+
73+
/**
74+
* The newest mtime under `roots`, or null when none of them exist.
75+
*
76+
* Skips `node_modules` (never watched, and the walk would dwarf everything else). A root that does
77+
* not exist is skipped rather than treated as an error: a fresh checkout has no `dist` yet, and
78+
* refusing to answer at all would turn "not built" into "not checked".
79+
*/
80+
async function newestModified(roots: readonly string[], base: string): Promise<{ atMs: number; path: string } | null> {
81+
let newest: { atMs: number; path: string } | null = null
82+
83+
async function walk(absolute: string): Promise<void> {
84+
let entries
85+
try {
86+
entries = await readdir(absolute, { withFileTypes: true })
87+
} catch {
88+
return
89+
}
90+
for (const entry of entries) {
91+
if (entry.name === 'node_modules' || entry.name.startsWith('.')) continue
92+
const child = path.join(absolute, entry.name)
93+
if (entry.isDirectory()) {
94+
if (IGNORED_DIRECTORIES.has(entry.name)) continue
95+
await walk(child)
96+
continue
97+
}
98+
if (IGNORED_SUFFIXES.some((suffix) => entry.name.endsWith(suffix))) continue
99+
try {
100+
const info = await stat(child)
101+
if (!newest || info.mtimeMs > newest.atMs) newest = { atMs: info.mtimeMs, path: path.relative(base, child) }
102+
} catch {
103+
// Raced with a rebuild deleting the file: the next scan sees the replacement.
104+
}
105+
}
106+
}
107+
108+
for (const root of roots) await walk(path.join(base, root))
109+
return newest
110+
}
111+
112+
/**
113+
* One scan, as a pure-ish function of its inputs: which trees to look at, what to measure them
114+
* against, and where the repo is. Parameterised for the test, which needs a controlled tree and a
115+
* controlled reference time; the watcher below passes the real ones.
116+
*
117+
* `startedAtMs` is a REFERENCE POINT, not "now": a watched file newer than it means the running
118+
* process cannot contain that file's contents.
119+
*/
120+
export async function evaluateSourceStaleness(options: {
121+
roots: readonly string[]
122+
startedAtMs: number
123+
root?: string
124+
}): Promise<DevSourceStaleness> {
125+
const base = options.root ?? repoRoot
126+
const newest = await newestModified(options.roots, base)
127+
const checkedAt = new Date().toISOString()
128+
if (!newest) return { stale: false, newestPath: null, newestModifiedAt: null, lastCheckedAt: checkedAt }
129+
return {
130+
stale: newest.atMs > options.startedAtMs,
131+
newestPath: newest.path,
132+
newestModifiedAt: new Date(newest.atMs).toISOString(),
133+
lastCheckedAt: checkedAt
134+
}
135+
}
136+
137+
async function scanOnce(): Promise<void> {
138+
const result = await evaluateSourceStaleness({ roots: WATCH_ROOTS, startedAtMs: processStartedAtMs })
139+
current = result
140+
if (!result.stale || !result.newestPath || !result.newestModifiedAt) {
141+
lastLoggedAt = 0
142+
return
143+
}
144+
const now = Date.now()
145+
if (lastLoggedAt !== 0 && now - lastLoggedAt < RELOG_INTERVAL_MS) return
146+
lastLoggedAt = now
147+
console.error(
148+
`[dev] THIS PROCESS IS RUNNING STALE CODE. ${result.newestPath} was modified ` +
149+
`${result.newestModifiedAt}, after this process started (${new Date(processStartedAtMs).toISOString()}). ` +
150+
'Its file watcher is not reloading it. Restart the dev stack before trusting anything you test against this server.'
151+
)
152+
}
153+
154+
/**
155+
* Begin watching, if this is a dev process. Safe to call unconditionally and idempotent per process.
156+
*
157+
* Fire and forget: it never throws into the caller and never blocks startup. A staleness monitor
158+
* that could delay or fail a boot would be worse than the problem it reports.
159+
*/
160+
export function startDevSourceStalenessWatch(): void {
161+
if (env.NODE_ENV === 'production') return
162+
void scanOnce().catch(() => {})
163+
const timer = setInterval(() => {
164+
void scanOnce().catch(() => {})
165+
}, SCAN_INTERVAL_MS)
166+
// Must never be the reason the process cannot exit.
167+
timer.unref()
168+
}
169+
170+
/** Current view, for the health endpoint. All-null before the first scan finishes. */
171+
export function devSourceStaleness(): DevSourceStaleness {
172+
return current
173+
}

‎apps/api/src/lib/print-dispatcher.ts‎

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ interface DispatchJobState {
112112
*/
113113
selectedPrintOptions: PrintStartOptionSelection
114114
/**
115-
* Instance `identify_id`s to skip (resolved from the request's `skipObjects` object
115+
* Instance `identify_id`s to skip (resolved from the request's `skipObjects` / `skipInstances`
116116
* ids at enqueue time), or null when the user deselected nothing. Sent as the start
117117
* command's `skip_objects` field (the primary mechanism: what Bambu Handy sends);
118118
* because older firmware ignores that field, runJob also arms a one-shot post-start
@@ -274,7 +274,7 @@ class PrintDispatcher {
274274
// nozzle the plate never uses (H2D error 0300-4010). Prune to the plate's actual
275275
// filaments; no-op for multi-filament plates and fail-safe if the plate can't be read.
276276
const amsMapping = await resolvePlateAmsMapping(sourceKind, localPath, input.plate, input.amsMapping)
277-
const postStartSkipObjectIds = await resolvePostStartSkipObjectIds(sourceKind, localPath, input.plate, input.skipObjects)
277+
const postStartSkipObjectIds = await resolvePostStartSkipObjectIds(sourceKind, localPath, input.plate, input.skipObjects, input.skipInstances)
278278

279279
const now = new Date()
280280
const target = getRemotePrintTarget(fileName, sourceKind, input.plate, plateName, { isMultiPlate })
@@ -988,9 +988,11 @@ async function resolvePlateAmsMapping(
988988
}
989989

990990
/**
991-
* Resolve the request's deselected plate objects (`skipObjects`, ids from the plates index the
992-
* print dialog displayed) into the instance `identify_id`s the firmware keys object skipping on
993-
* (both the start command's `skip_objects` field and the mid-print command).
991+
* Resolve the request's deselection into the instance `identify_id`s the firmware keys object
992+
* skipping on (both the start command's `skip_objects` field and the mid-print command). The
993+
* selection arrives in two id spaces over the same file and both are honoured: `skipObjects`
994+
* names whole models by the plates index's `objects[].id`, and `skipInstances` names individual
995+
* placements by `identify_id` (what lets a user skip one of eight copies).
994996
*
995997
* Resolution MUST go through the same shared index parse that produced the dialog's object list
996998
* ({@link readPlateIndex}), never a direct `model_settings.config` lookup: gcode-only exports
@@ -1009,9 +1011,10 @@ async function resolvePostStartSkipObjectIds(
10091011
sourceKind: '3mf' | 'gcode',
10101012
localPath: string | null,
10111013
plate: number,
1012-
skipObjects: number[] | undefined
1014+
skipObjects: number[] | undefined,
1015+
skipInstances: number[] | undefined
10131016
): Promise<number[] | null> {
1014-
if (!skipObjects || skipObjects.length === 0) return null
1017+
if ((!skipObjects || skipObjects.length === 0) && (!skipInstances || skipInstances.length === 0)) return null
10151018
if (sourceKind !== '3mf') {
10161019
throw new Error('Object skipping is only available for sliced 3MF files')
10171020
}
@@ -1026,8 +1029,8 @@ async function resolvePostStartSkipObjectIds(
10261029
if (!index) {
10271030
throw new Error('Could not read the file to resolve the deselected objects. Try again, or print without deselecting objects.')
10281031
}
1029-
const mapped = plateSkipIdentifyIdsFromIndex(index, plate, new Set(skipObjects))
1030-
if (mapped.unmatchedObjectIds.length > 0 || mapped.identifyIds.length === 0) {
1032+
const mapped = plateSkipIdentifyIdsFromIndex(index, plate, new Set(skipObjects), new Set(skipInstances))
1033+
if (mapped.unmatchedObjectIds.length > 0 || mapped.unmatchedInstanceIds.length > 0 || mapped.identifyIds.length === 0) {
10311034
throw new Error('Some deselected objects could not be matched on the selected plate. Re-open the print dialog and try again.')
10321035
}
10331036
if (mapped.identifyIds.length >= mapped.plateInstanceCount) {

0 commit comments

Comments
 (0)