@helpra/design 0.1.0 → 0.1.3

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 (37) hide show
  1. package/README.md +71 -58
  2. package/design-system/helpra/tokens.json +56 -118
  3. package/dist/embed/types.d.ts +2 -2
  4. package/dist/ui/assets/browserHost-DO0VE7SS.js +1 -0
  5. package/dist/ui/assets/{index-DCndCScv.js → index-B0caw0Dc.js} +10 -10
  6. package/dist/ui/assets/session.schemas-o3W88yfn.js +352 -0
  7. package/dist/ui/index.html +1 -1
  8. package/docs/orca-integration.md +1 -1
  9. package/package.json +2 -1
  10. package/src/contracts/agent-targets.ts +1 -1
  11. package/src/contracts/publication-publish.schemas.ts +2 -2
  12. package/src/contracts/publication.schemas.ts +1 -1
  13. package/src/contracts/publication.types.ts +1 -1
  14. package/src/embed/types.ts +2 -2
  15. package/src/project/dependencies.ts +10 -2
  16. package/src/project/git-commit.ts +1 -2
  17. package/src/project/git.ts +4 -7
  18. package/src/project/watch.ts +20 -11
  19. package/src/publication/cutover.ts +12 -6
  20. package/src/publication/store.constants.ts +2 -2
  21. package/src/publication/validate-store.ts +5 -3
  22. package/src/render/build.ts +6 -5
  23. package/src/render/index.ts +3 -3
  24. package/src/render/vite-build.ts +5 -6
  25. package/src/review/storage.ts +17 -2
  26. package/src/service/agent/dispatch.ts +2 -2
  27. package/src/service/agent/orca.ts +12 -1
  28. package/src/service/agent/payload.ts +1 -1
  29. package/src/source-export/job-store.ts +14 -8
  30. package/src/ui/HomeRecents.tsx +8 -52
  31. package/src/ui/ProjectDialog.tsx +3 -1
  32. package/src/ui/ThreadDetail.tsx +10 -7
  33. package/src/ui/agentDelivery.ts +1 -1
  34. package/src/ui/browserHost.ts +1 -1
  35. package/src/ui/system/ScreenConstantsSection.tsx +1 -1
  36. package/dist/ui/assets/browserHost-CgiYo1Ht.js +0 -1
  37. package/dist/ui/assets/session.schemas-DqTxSFE-.js +0 -352
package/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "@helpra/design",
3
- "version": "0.1.0",
3
+ "version": "0.1.3",
4
+ "author": "Helpra <support@helpra.app>",
4
5
  "homepage": "https://design.helpra.app",
5
6
  "repository": {
6
7
  "type": "git",
@@ -29,7 +29,7 @@ export const dispatchDestinationSchema = /* @__PURE__ */ (() => z.strictObject({
29
29
  ideId: idSchema.max(64).optional(),
30
30
  targetRef: z.string().min(1).max(200).optional(),
31
31
  hostTarget: z.string().min(1).max(200).optional(),
32
- hostKind: z.enum(['orca', 'helpra-works']).optional(),
32
+ hostKind: z.enum(['orca', 'desktop']).optional(),
33
33
  }).refine(value => Boolean(value.hostTarget) === Boolean(value.hostKind)
34
34
  && !(value.ideId && value.hostTarget) && (!value.targetRef || Boolean(value.ideId)),
35
35
  'Choose one destination'))();
@@ -8,14 +8,14 @@ const digest = revisionSchema.length(71);
8
8
  export const publishOperationIdSchema = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}(?![\s\S])/);
9
9
  export const publicationPublishInputSchema = z.strictObject({
10
10
  operationId: publishOperationIdSchema,
11
- repository: z.literal('helpra/helpra-artifacts/design'), branch: z.literal('dev'), sourceCommit: commit,
11
+ repository: z.literal('example-org/design-assets'), branch: z.literal('dev'), sourceCommit: commit,
12
12
  expected: z.strictObject({ sourceCommit: commit, storeTreeDigest: digest }),
13
13
  });
14
14
  const catalog = (projectId: string) => z.strictObject({ projectId: z.literal(projectId), contentRevision: digest, sourceTreeDigest: digest });
15
15
  export const publicationPublishReceiptSchema = z.strictObject({
16
16
  sourceCommit: commit, observedRevision: commit, storeTreeDigest: digest, guide: guideIdentitySchema.extend({ sha256: digest }),
17
17
  catalogs: z.strictObject({
18
- business: catalog('project-efd0ea9e-eb78-4334-a3c1-9cbb01a088d9'), works: catalog('project-helpra-works-catalog'),
18
+ business: catalog('project-example-business'), works: catalog('project-example-workspace'),
19
19
  }),
20
20
  }).refine(value => value.sourceCommit === value.observedRevision && value.guide.version === `git:${value.sourceCommit}`, 'Receipt must describe one verified generation');
21
21
  export const publicationPublishErrorSchema = z.enum([
@@ -3,7 +3,7 @@ import { idSchema, revisionSchema } from './common.js';
3
3
  export const guideIdentitySchema = z.strictObject({ version: z.string().regex(/^(?:git:[a-f0-9]{40}|content:[a-f0-9]{64})$/), sha256: revisionSchema });
4
4
  export const publishedCatalogSchema = z.strictObject({
5
5
  catalogId: z.enum(['business', 'works']), projectId: idSchema,
6
- source: z.strictObject({ kind: z.literal('git'), repository: z.literal('helpra/helpra-artifacts/design'), branch: z.literal('dev'), gitCommit: z.string().regex(/^[a-f0-9]{40}$/) }),
6
+ source: z.strictObject({ kind: z.literal('git'), repository: z.literal('example-org/design-assets'), branch: z.literal('dev'), gitCommit: z.string().regex(/^[a-f0-9]{40}$/) }),
7
7
  contentRevision: revisionSchema, sourceTreeDigest: revisionSchema, servedAt: z.iso.datetime(), observedRevision: z.string().regex(/^[a-f0-9]{40}$/).optional(),
8
8
  });
9
9
  export const publicationMetadataSchema = publishedCatalogSchema.extend({ checkedAt: z.iso.datetime(), lastAttempt: z.enum(['ok', 'pending', 'error']), freshness: z.enum(['current', 'update_pending', 'stale', 'error']), errorCode: z.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(), guide: guideIdentitySchema, storeTreeDigest: revisionSchema });
@@ -20,6 +20,6 @@ export interface PublicationReceipt {
20
20
  durable: { reviewDigest: string; localDigest: string; exportsDigest: string };
21
21
  }
22
22
  export interface StorePublicationReceipt {
23
- schemaVersion: 1; repository: 'helpra/helpra-artifacts/design'; branch: 'dev'; gitCommit: string; sourceTreeDigest: string;
23
+ schemaVersion: 1; repository: 'example-org/design-assets'; branch: 'dev'; gitCommit: string; sourceTreeDigest: string;
24
24
  catalogs: Record<CatalogId, PublicationReceipt>; guide: GuideIdentity;
25
25
  }
@@ -8,7 +8,7 @@ export interface DesignAgentTarget {
8
8
  export interface AgentCommentDispatchPayload {
9
9
  schemaVersion: 1;
10
10
  dispatchId: string;
11
- host: 'orca' | 'helpra-works' | 'local-cli' | 'remote-webhook';
11
+ host: 'orca' | 'desktop' | 'local-cli' | 'remote-webhook';
12
12
  targetAgentId: string;
13
13
  project: { projectId: string; workingCopyId: string; name: string; contentRevision: string };
14
14
  artboard: {
@@ -30,7 +30,7 @@ export type EmbedContextMenuKind = 'empty_canvas' | 'artboard' | 'nav_page' | 'n
30
30
  | 'home_item' | 'region_or_element' | 'comment_thread' | 'approval_row' | 'design_system_item' | 'text_input';
31
31
 
32
32
  export interface HelpraDesignHostContext {
33
- host: 'orca' | 'helpra-works';
33
+ host: 'orca' | 'desktop';
34
34
  authMode: 'trusted-local';
35
35
  theme: string;
36
36
  locale: 'ru' | 'en';
@@ -94,10 +94,18 @@ function collectReferences(relative: string, source: string, budget: ProjectRead
94
94
  }
95
95
 
96
96
  async function resolveDependency(root: string, candidates: string[], budget?: ProjectReadBudget, designSystemRoot?: string): Promise<string | undefined> {
97
+ let caseMismatch: DesignError | undefined;
97
98
  for (const relative of candidates) {
98
- const filename = await resolveProjectPath(root, relative, { budget, designSystemRoot });
99
- try { if ((await lstat(filename)).isFile()) return relative; } catch (error) { if (!isMissing(error)) throw error; }
99
+ try {
100
+ const filename = await resolveProjectPath(root, relative, { budget, designSystemRoot });
101
+ if ((await lstat(filename)).isFile()) return relative;
102
+ } catch (error) {
103
+ // A case-insensitive disk can find a different file before a valid extension substitution.
104
+ if (error instanceof DesignError && error.code === 'source_conflict') caseMismatch ??= error;
105
+ else if (!isMissing(error)) throw error;
106
+ }
100
107
  }
108
+ if (caseMismatch) throw caseMismatch;
101
109
  return undefined;
102
110
  }
103
111
 
@@ -1,4 +1,3 @@
1
- import { devNull } from 'node:os';
2
1
  import { lstat } from 'node:fs/promises';
3
2
  import type { z } from 'zod';
4
3
  import { DesignError } from '../contracts/common.js';
@@ -24,7 +23,7 @@ export async function commitDesignPaths(workspace: WorkspaceService, input: z.ou
24
23
  }
25
24
  const repository = await inspectGit(root);
26
25
  if (!repository.gitRoot || repository.designSubdir?.startsWith('..')) throw new DesignError('git_unavailable', 'Project has no containing local Git repository');
27
- const run = (args: string[]) => git(['--literal-pathspecs', '-C', root, '-c', 'commit.gpgSign=false', '-c', `core.attributesFile=${devNull}`,
26
+ const run = (args: string[]) => git(['--literal-pathspecs', '-C', root, '-c', 'commit.gpgSign=false', '-c', 'core.attributesFile=/dev/null',
28
27
  '-c', 'gc.auto=0', '-c', 'maintenance.auto=false', '-c', 'protocol.allow=never', ...args]);
29
28
  const newPaths = [];
30
29
  const known = new Set(revision.files.map(file => file.path));
@@ -2,16 +2,15 @@ import { publicGitOptions } from './public-git.js';
2
2
  import { execFile } from 'node:child_process';
3
3
  import { lstat, mkdir, readdir, realpath } from 'node:fs/promises';
4
4
  import path from 'node:path';
5
- import { devNull } from 'node:os';
6
5
  import { promisify } from 'node:util';
7
6
  import type { ProjectReadBudget } from '../contracts/project-read.types.js';
8
7
  import { DesignError } from '../contracts/common.js';
9
8
  import { assertRelativePath, isMissing, resolveProjectPath } from './paths.js';
10
9
 
11
10
  const execute = promisify(execFile);
12
- const GIT_OPTIONS = ['-c', `core.hooksPath=${devNull}`, '-c', 'core.fsmonitor=false', '-c', 'protocol.allow=never', '-c', 'protocol.https.allow=always', '-c', 'protocol.ssh.allow=always', '-c', 'protocol.file.allow=always'];
11
+ const GIT_OPTIONS = ['-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false', '-c', 'protocol.allow=never', '-c', 'protocol.https.allow=always', '-c', 'protocol.ssh.allow=always', '-c', 'protocol.file.allow=always'];
13
12
  function gitEnvironment(): NodeJS.ProcessEnv {
14
- return { PATH: process.env.PATH, HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE, SystemRoot: process.env.SystemRoot, SSH_AUTH_SOCK: process.env.SSH_AUTH_SOCK, LANG: 'C', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: devNull, GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0' };
13
+ return { PATH: process.env.PATH ?? process.env.Path, HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE, SystemRoot: process.env.SystemRoot ?? process.env.SYSTEMROOT, SSH_AUTH_SOCK: process.env.SSH_AUTH_SOCK, LANG: 'C', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0' };
15
14
  }
16
15
  export async function git(args: string[], timeout = 15_000, env: NodeJS.ProcessEnv = {}): Promise<string> {
17
16
  const result = await execute('git', [...GIT_OPTIONS, ...args], { env: { ...gitEnvironment(), ...env }, windowsHide: true, timeout, maxBuffer: 1024 * 1024 });
@@ -23,11 +22,9 @@ export async function inspectGit(root: string, budget?: ProjectReadBudget): Prom
23
22
  const designRoot = await realpath(root);
24
23
  let gitRoot: string;
25
24
  try { gitRoot = await realpath(await git(['-C', designRoot, 'rev-parse', '--show-toplevel'], Math.min(15_000, budget?.timeLeft() ?? 15_000))); }
26
- catch (error) {
25
+ catch {
27
26
  budget?.check();
28
- if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') return {};
29
- if (typeof error === 'object' && error !== null && 'stderr' in error && typeof error.stderr === 'string' && error.stderr.includes('not a git repository')) return {};
30
- throw new DesignError('service_unavailable', 'Git metadata could not be inspected');
27
+ return {};
31
28
  }
32
29
  let gitCommit: string | undefined;
33
30
  try { gitCommit = await git(['-C', designRoot, 'rev-parse', '--verify', 'HEAD'], Math.min(15_000, budget?.timeLeft() ?? 15_000)); }
@@ -32,6 +32,7 @@ export function watchProject(options: {
32
32
  let running = false;
33
33
  const changed = new Set<string>();
34
34
  const suppressed = new Map<string, WrittenFileStat & { expiresAt: number }>();
35
+ const deferred = new Map<string, ReturnType<typeof setTimeout>>();
35
36
 
36
37
  const sourceLocked = async (): Promise<boolean> => {
37
38
  try {
@@ -113,6 +114,7 @@ export function watchProject(options: {
113
114
  }
114
115
  try {
115
116
  const stat = await lstat(filename, { bigint: true });
117
+ if (entry !== suppressed.get(relative)) return isSuppressedSelfWrite(relative, filename);
116
118
  if (
117
119
  !entry.removed && stat.dev === entry.dev &&
118
120
  stat.ino === entry.ino &&
@@ -122,21 +124,26 @@ export function watchProject(options: {
122
124
  return true;
123
125
  }
124
126
  } catch (error) {
127
+ if (entry !== suppressed.get(relative)) return isSuppressedSelfWrite(relative, filename);
125
128
  if (entry.removed && isMissing(error)) return true;
126
129
  }
127
- suppressed.delete(relative);
128
130
  return false;
129
131
  };
130
132
 
131
- const onFsEvent = (relative: string, filename: string): void => {
132
- if (closed) return;
133
- if (suppressed.has(relative)) {
134
- void isSuppressedSelfWrite(relative, filename).then((ignored) => {
135
- if (ignored || closed) return;
136
- options.onExternalChange?.(relative);
137
- schedule(relative);
138
- });
139
- return;
133
+ const onFsEvent = async (relative: string, filename: string): Promise<void> => {
134
+ if (closed || deferred.has(relative)) return;
135
+ try {
136
+ // A transaction may have replaced the path but not yet reported its write.
137
+ if (await sourceLocked()) {
138
+ if (!closed && !deferred.has(relative)) deferred.set(relative, setTimeout(() => {
139
+ deferred.delete(relative);
140
+ void onFsEvent(relative, filename);
141
+ }, 75));
142
+ return;
143
+ }
144
+ if (await isSuppressedSelfWrite(relative, filename) || closed) return;
145
+ } catch {
146
+ if (closed) return;
140
147
  }
141
148
  options.onExternalChange?.(relative);
142
149
  schedule(relative);
@@ -166,7 +173,7 @@ export function watchProject(options: {
166
173
  });
167
174
  watcher.on('all', (event, filename) => {
168
175
  // Empty directories are outside the revision inventory. Chokidar reports their files separately.
169
- if (event !== 'addDir') onFsEvent(relativeTo(options.root, filename), filename);
176
+ if (event !== 'addDir') void onFsEvent(relativeTo(options.root, filename), filename);
170
177
  });
171
178
  watcher.on('error', onWatchError);
172
179
 
@@ -210,6 +217,8 @@ export function watchProject(options: {
210
217
  async close() {
211
218
  closed = true;
212
219
  if (timer) clearTimeout(timer);
220
+ for (const check of deferred.values()) clearTimeout(check);
221
+ deferred.clear();
213
222
  suppressed.clear();
214
223
  await Promise.all([watcher.close(), designSystemWatcher?.close()]);
215
224
  },
@@ -1,5 +1,5 @@
1
1
  import { constants } from 'node:fs';
2
- import { open, realpath } from 'node:fs/promises';
2
+ import { lstat, open, realpath } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { DesignError } from '../contracts/common.js';
5
5
  import type { PublicationReceipt, StorePublicationReceipt } from '../contracts/publication.types.js';
@@ -41,11 +41,17 @@ export async function prepareCutoverPublication(root: string, gitCommit: string,
41
41
 
42
42
  /** The host mounts this private file separately, read-only; the project cannot supply it. */
43
43
  export async function readCutoverProof(filename: string, candidate: string): Promise<CutoverProof> {
44
- if (contained(await realpath(candidate), path.resolve(filename)) || contained(await realpath(candidate), await realpath(filename))) invalid();
45
- const handle = await open(filename, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
44
+ const root = await realpath(candidate);
45
+ const initial = await lstat(filename, { bigint: true });
46
+ const canonical = await realpath(filename);
47
+ if (!initial.isFile() || contained(root, path.resolve(filename)) || contained(root, canonical)) invalid();
48
+ const handle = await open(filename, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
46
49
  try {
47
- const stat = await handle.stat();
48
- if (!stat.isFile() || stat.nlink !== 1 || stat.size > 32 * 1024 * 1024) invalid();
50
+ const stat = await handle.stat({ bigint: true });
51
+ const current = await lstat(filename, { bigint: true });
52
+ if (!stat.isFile() || stat.nlink !== 1n || stat.size > 32n * 1024n * 1024n ||
53
+ stat.dev !== initial.dev || stat.ino !== initial.ino || !current.isFile() ||
54
+ stat.dev !== current.dev || stat.ino !== current.ino || await realpath(filename) !== canonical) invalid();
49
55
  return cutoverProofSchema.parse(JSON.parse((await handle.readFile()).toString('utf8')) as unknown);
50
56
  } finally { await handle.close(); }
51
57
  }
@@ -75,7 +81,7 @@ export async function validateAssembledPublication(root: string, gitCommit: stri
75
81
  await provePortableSource(root, proof);
76
82
  if (JSON.stringify(guide.identity) !== JSON.stringify(proof.guide)) invalid();
77
83
  return {
78
- schemaVersion: 1, repository: 'helpra/helpra-artifacts/design', branch: 'dev', gitCommit,
84
+ schemaVersion: 1, repository: 'example-org/design-assets', branch: 'dev', gitCommit,
79
85
  sourceTreeDigest: proof.sourceTreeDigest, guide: guide.identity,
80
86
  catalogs: { business: { ...proof.catalogs.business, ...business }, works: { ...proof.catalogs.works, ...works } },
81
87
  };
@@ -1,6 +1,6 @@
1
1
  export const NATIVE_CATALOGS = {
2
- business: { projectId: 'project-efd0ea9e-eb78-4334-a3c1-9cbb01a088d9' },
3
- works: { projectId: 'project-helpra-works-catalog' },
2
+ business: { projectId: 'project-example-business' },
3
+ works: { projectId: 'project-example-workspace' },
4
4
  } as const;
5
5
  export const CATALOG_DIRECTORY = 'design-catalog';
6
6
  export const STORE_GUIDE_PATH = `${CATALOG_DIRECTORY}/skills/helpra-design`;
@@ -1,4 +1,5 @@
1
1
  import path from 'node:path';
2
+ import { realpath } from 'node:fs/promises';
2
3
  import type { ProjectTopology } from '../contracts/project.js';
3
4
  import type { StorePublicationReceipt, CatalogId } from '../contracts/publication.types.js';
4
5
  import { DesignError } from '../contracts/common.js';
@@ -10,8 +11,9 @@ import { CATALOG_DIRECTORY, NATIVE_CATALOGS, STORE_DURABLE_PATHS, STORE_GUIDE_PA
10
11
  import { validatePublication } from './validate.js';
11
12
 
12
13
  export async function validateStorePublication(root: string, gitCommit: string, onTopology?: (catalog: CatalogId, topology: ProjectTopology) => void): Promise<StorePublicationReceipt> {
13
- const git = await inspectGit(root);
14
- if (git.gitRoot !== path.resolve(root) || git.gitCommit !== gitCommit) throw new DesignError('publication_invalid', 'Store must be the exact common Git checkout');
14
+ const canonicalRoot = await realpath(root);
15
+ const git = await inspectGit(canonicalRoot);
16
+ if (git.gitRoot !== canonicalRoot || git.gitCommit !== gitCommit) throw new DesignError('publication_invalid', 'Store must be the exact common Git checkout');
15
17
  const business = await validatePublication(path.join(root, CATALOG_DIRECTORY, 'business'), NATIVE_CATALOGS.business.projectId, gitCommit, true, topology => onTopology?.('business', topology));
16
18
  const works = await validatePublication(path.join(root, CATALOG_DIRECTORY, 'works'), NATIVE_CATALOGS.works.projectId, gitCommit, true, topology => onTopology?.('works', topology));
17
19
  const guide = await readGuideBundle(path.join(root, STORE_GUIDE_PATH), gitCommit);
@@ -19,5 +21,5 @@ export async function validateStorePublication(root: string, gitCommit: string,
19
21
  if (!source.some(file => file.path.startsWith('design-system/'))) throw new DesignError('publication_invalid', 'Shared system source is missing');
20
22
  if (source.some(file => isForbiddenSourcePath(file.path) && !(file.path.split('/').at(-1) === '.gitkeep' && file.size === 0) && !STORE_METADATA_PATHS.some(relative => relative === file.path))) throw new DesignError('publication_invalid', 'Store contains a private portable source member');
21
23
  await assertPublishedGitSource(root, source.map(file => file.path), gitCommit);
22
- return { schemaVersion: 1, repository: 'helpra/helpra-artifacts/design', branch: 'dev', gitCommit, sourceTreeDigest: membersDigest(source), catalogs: { business, works }, guide: guide.identity };
24
+ return { schemaVersion: 1, repository: 'example-org/design-assets', branch: 'dev', gitCommit, sourceTreeDigest: membersDigest(source), catalogs: { business, works }, guide: guide.identity };
23
25
  }
@@ -10,14 +10,13 @@ import { tokenCssName } from '../system/token-values.js';
10
10
  import { expandHtmlFragments } from '../project/html-fragments.js';
11
11
  import { inputReferences } from './input-references.js';
12
12
  import { assertAssetClosure } from './asset-safety.js';
13
- import { isForbiddenSourcePath, validateCanonicalDirectory } from '../project/paths.js';
13
+ import { contained, isForbiddenSourcePath, validateCanonicalDirectory } from '../project/paths.js';
14
14
  import type { ViteBuildParams } from './vite-build.js';
15
15
  import type { BuildInput, BuiltOutput } from './build.types.js';
16
16
 
17
17
  export function permittedFile(file: string): boolean {
18
18
  return relativePathSchema.safeParse(file).success && !isForbiddenSourcePath(file);
19
19
  }
20
- const inside = (root: string, file: string): boolean => file === root || file.startsWith(root + path.sep);
21
20
  const scriptJson = (value: unknown): string => JSON.stringify(value).replaceAll('<', '\\u003c');
22
21
  async function outputFiles(root: string, prefix = ''): Promise<string[]> {
23
22
  const entries = await readdir(path.join(root, prefix), { withFileTypes: true });
@@ -41,11 +40,13 @@ export async function buildPreview(input: BuildInput, runBuild: (params: ViteBui
41
40
  inputs = new Map(inputs).set(entry, Buffer.from(expanded));
42
41
  }
43
42
  if (!/^render-[a-f0-9-]{36}$/.test(record.renderId)) throw new DesignError('invalid_input', 'Invalid build identity');
44
- const buildsRoot = path.resolve(input.stateDir, 'builds');
43
+ await mkdir(input.stateDir, { recursive: true });
44
+ const buildsRoot = path.join(await realpath(input.stateDir), 'builds');
45
+ await mkdir(buildsRoot, { recursive: true });
46
+ await validateCanonicalDirectory(buildsRoot, { requireCanonical: true });
45
47
  const buildRoot = path.join(buildsRoot, record.renderId);
46
48
  const inputRoot = path.join(buildRoot, 'input');
47
49
  const outDir = path.join(buildRoot, 'output');
48
- await mkdir(buildsRoot, { recursive: true });
49
50
  // Exclusive ownership precedes cleanup: existing previews or active jobs are never ours.
50
51
  await mkdir(buildRoot);
51
52
  let complete = false;
@@ -120,6 +121,6 @@ export async function buildPreview(input: BuildInput, runBuild: (params: ViteBui
120
121
  export async function readBuiltFile(output: BuiltOutput, file: string): Promise<Uint8Array> {
121
122
  if (!output.files.includes(file) || !permittedFile(file)) throw new DesignError('forbidden_path', 'Preview file is not in the output allowlist');
122
123
  const resolved = await realpath(path.join(output.root, file));
123
- if (!inside(output.root, resolved)) throw new DesignError('symlink_escape', 'Output file escaped render root');
124
+ if (!contained(output.root, resolved)) throw new DesignError('symlink_escape', 'Output file escaped render root');
124
125
  return readFile(resolved);
125
126
  }
@@ -1,6 +1,6 @@
1
1
  import { validateOrigins } from '../contracts/origins.js';
2
2
  import { randomUUID } from 'node:crypto';
3
- import { access, cp, mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises';
3
+ import { access, cp, mkdir, readFile, readdir, realpath, rename, rm, writeFile } from 'node:fs/promises';
4
4
  import path from 'node:path';
5
5
  import { DesignError, type Diagnostic } from '../contracts/common.js';
6
6
  import { renderRecordSchema, renderRequestSchema, type AnnotationProvider, type DomInspection, type RenderRecord, type RenderRequest } from '../contracts/render.js';
@@ -46,7 +46,7 @@ async function cloneBuiltOutput(
46
46
  await access(sourceEntryPath);
47
47
  const entryHtml = await readFile(sourceEntryPath, 'utf8');
48
48
  if (!entryHtml.includes(sourceRecord.renderId) || !entryHtml.includes(sourceRecord.channelId)) return undefined;
49
- const buildRoot = path.join(path.resolve(stateDir, 'builds'), targetRecord.renderId);
49
+ const buildRoot = path.join(await realpath(stateDir), 'builds', targetRecord.renderId);
50
50
  const outDir = path.join(buildRoot, 'output');
51
51
  await mkdir(buildRoot, { recursive: true });
52
52
  try {
@@ -147,7 +147,7 @@ export function createRendererService(options: RendererOptions): LocalRendererSe
147
147
  try {
148
148
  const unknown: unknown = JSON.parse(await readFile(path.join(options.stateDir, 'renders', `${id}.output.json`), 'utf8'));
149
149
  const stored = persistedBuiltOutputSchema.parse(unknown);
150
- const restored = { ...stored, root: path.resolve(options.stateDir, 'builds', id, 'output') };
150
+ const restored = { ...stored, root: path.join(await realpath(options.stateDir), 'builds', id, 'output') };
151
151
  remember(outputs, id, restored, 128); return restored;
152
152
  } catch { throw new DesignError('render_not_found', 'Rendered output metadata is missing or corrupt'); }
153
153
  };
@@ -8,7 +8,7 @@ import lucidePackage from 'lucide-react/package.json' with { type: 'json' };
8
8
  import { build, type Plugin } from 'vite';
9
9
  import { DesignError, relativePathSchema } from '../contracts/common.js';
10
10
  import { COMPONENT_BARREL, COMPONENT_LIBRARY } from '../project/component-library.js';
11
- import { isForbiddenSourcePath } from '../project/paths.js';
11
+ import { contained, isForbiddenSourcePath } from '../project/paths.js';
12
12
  import { CONTROLLED_MODULES } from './module-policy.constants.js';
13
13
 
14
14
  export interface ViteBuildParams {
@@ -25,7 +25,6 @@ const require = createRequire(import.meta.url);
25
25
  const packageRoot = (name: string): string => path.dirname(realpathSync(require.resolve(`${name}/package.json`)));
26
26
  const lucideRoot = packageRoot('lucide-react');
27
27
  const dependencyRoots = [packageRoot('react'), packageRoot('react-dom'), packageRoot('scheduler'), lucideRoot];
28
- const inside = (root: string, file: string): boolean => file === root || file.startsWith(root + path.sep);
29
28
  const permitted = (file: string): boolean => relativePathSchema.safeParse(file).success && !isForbiddenSourcePath(file);
30
29
 
31
30
  function guardPlugin(
@@ -58,7 +57,7 @@ function guardPlugin(
58
57
  return path.join(inputRoot, member);
59
58
  }
60
59
  if (source === 'lucide-react') return path.join(lucideRoot, lucidePackage.module);
61
- if (!source.startsWith('.') && !source.startsWith('/') && !CONTROLLED_MODULES.has(source)) fail('unresolved_dependency', `Dependency ${source} is not in the controlled renderer`);
60
+ if (!source.startsWith('.') && !path.isAbsolute(source) && !CONTROLLED_MODULES.has(source)) fail('unresolved_dependency', `Dependency ${source} is not in the controlled renderer`);
62
61
  if (CONTROLLED_MODULES.has(source)) return require.resolve(source);
63
62
  return null;
64
63
  },
@@ -67,9 +66,9 @@ function guardPlugin(
67
66
  const file = id.split('?')[0];
68
67
  if (!file || !path.isAbsolute(file)) return null;
69
68
  const resolved = await realpath(file);
70
- if (!inside(inputRoot, resolved) && !allowedRoots.some((root) => inside(root, resolved))) fail('path_outside_root', 'Build import escaped immutable inputs');
71
- if (inside(inputRoot, resolved) && !permitted(path.relative(inputRoot, resolved).split(path.sep).join('/'))) fail('forbidden_path', 'Build import is private');
72
- if (designSystemRoot && inside(designSystemRoot, resolved) && !permitted(path.relative(designSystemRoot, resolved).split(path.sep).join('/'))) fail('forbidden_path', 'Design system build import is private');
69
+ if (!contained(inputRoot, resolved) && !allowedRoots.some((root) => contained(root, resolved))) fail('path_outside_root', 'Build import escaped immutable inputs');
70
+ if (contained(inputRoot, resolved) && !permitted(path.relative(inputRoot, resolved).split(path.sep).join('/'))) fail('forbidden_path', 'Build import is private');
71
+ if (designSystemRoot && contained(designSystemRoot, resolved) && !permitted(path.relative(designSystemRoot, resolved).split(path.sep).join('/'))) fail('forbidden_path', 'Design system build import is private');
73
72
  return null;
74
73
  },
75
74
  };
@@ -192,6 +192,15 @@ export class ReviewStore {
192
192
  try {
193
193
  for (let attempt = 0; attempt < 100; attempt++) {
194
194
  try {
195
+ if (process.platform === 'win32') {
196
+ // A directory rename on Windows can replace a legacy file lock.
197
+ const existing = await lstat(key).catch((error: unknown) => { if (!hasCode(error, 'ENOENT')) throw error; });
198
+ if (existing && !existing.isDirectory()) {
199
+ await this.removeDeadLock(key);
200
+ await delay(20);
201
+ continue;
202
+ }
203
+ }
195
204
  // Publish a populated directory atomically; neither acquisition nor recovery exposes an empty owner record.
196
205
  const token = randomUUID();
197
206
  const temporary = join(lockDirectory, `.lock-${token}`);
@@ -212,7 +221,7 @@ export class ReviewStore {
212
221
  cleanupPath = temporary;
213
222
  return release;
214
223
  } catch (error) {
215
- if (!['EEXIST', 'ENOTEMPTY', 'ENOTDIR'].some((code) => hasCode(error, code))) throw error;
224
+ if (!directoryCollision(error) && !hasCode(error, 'ENOTDIR')) throw error;
216
225
  await this.removeDeadLock(key);
217
226
  await delay(20);
218
227
  }
@@ -245,7 +254,7 @@ export class ReviewStore {
245
254
  if (!hasCode(error, 'ESRCH')) return;
246
255
  // Keep the nonempty tombstone: another reaper holding this old token cannot rename a new live lock over it.
247
256
  try { await rename(path, `${path}.retired-${owner.token}`); }
248
- catch (renameError) { if (!['ENOENT', 'EEXIST', 'ENOTEMPTY'].some((code) => hasCode(renameError, code))) throw renameError; }
257
+ catch (renameError) { if (!hasCode(renameError, 'ENOENT') && !directoryCollision(renameError)) throw renameError; }
249
258
  }
250
259
  } catch (error) { if (!hasCode(error, 'ENOENT')) throw error; }
251
260
  }
@@ -255,3 +264,9 @@ export class ReviewStore {
255
264
  function hasCode(error: unknown, code: string): boolean {
256
265
  return error instanceof Error && 'code' in error && error.code === code;
257
266
  }
267
+
268
+ function directoryCollision(error: unknown): boolean {
269
+ return hasCode(error, 'EEXIST') || hasCode(error, 'ENOTEMPTY') ||
270
+ (process.platform === 'win32' && error instanceof Error &&
271
+ 'syscall' in error && error.syscall === 'rename' && hasCode(error, 'EPERM'));
272
+ }
@@ -32,7 +32,7 @@ type Browser = { session: string; origin: string; userAgent: string; hostEnabled
32
32
  type Recipient = Pick<DispatchReceipt, 'targetId' | 'targetName' | 'recipient'>;
33
33
 
34
34
  function hostName(kind: DispatchDestination['hostKind']): string {
35
- return kind === 'orca' ? 'Orca' : 'Helpra Works';
35
+ return kind === 'orca' ? 'Orca' : 'Desktop';
36
36
  }
37
37
 
38
38
  export class AgentDispatchService {
@@ -193,7 +193,7 @@ export class AgentDispatchService {
193
193
 
194
194
  if (native) {
195
195
  try {
196
- const payload = await this.payload(saved, saved.targetName === hostName('orca') ? 'orca' : 'helpra-works');
196
+ const payload = await this.payload(saved, saved.targetName === hostName('orca') ? 'orca' : 'desktop');
197
197
  const started = await this.claim(saved);
198
198
  return started ? { dispatch, payload, attempt: saved.attempt } : { dispatch };
199
199
  } catch {
@@ -32,10 +32,21 @@ export async function resolveOrcaCli(platform = process.platform, env = process.
32
32
  return undefined;
33
33
  }
34
34
 
35
+ const callerSessionVariables = new Set([
36
+ 'ORCA_AGENT_SESSION_ID', 'ORCA_AGENT_SESSION_SPAWN_TOKEN', 'ORCA_BOT_TOOLS_TOKEN',
37
+ 'ORCA_STRUCTURED_SESSION', 'ORCA_SESSION_ID', 'ORCA_DISPATCH_ID', 'ORCA_TASK_ID',
38
+ 'ORCA_CONSUMER_ID', 'ORCA_CONVERSATION_ID', 'ORCA_BOT_ID', 'ORCA_BOT_NAME',
39
+ ]);
40
+
35
41
  export type OrcaCommand = (args: string[]) => Promise<unknown>;
36
42
  export function orcaCommand(executable: string): OrcaCommand {
37
43
  return async args => {
38
- const { stdout } = await promisify(execFile)(executable, args, { timeout: 3000, maxBuffer: 16 * 1024 * 1024, windowsHide: true }).catch((error: unknown) => {
44
+ // Delivery identifies itself as Helpra Design even when launched from an Orca agent session.
45
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) =>
46
+ !callerSessionVariables.has(process.platform === 'win32' ? key.toUpperCase() : key)));
47
+ const { stdout } = await promisify(execFile)(executable, args, {
48
+ env, timeout: 3000, maxBuffer: 16 * 1024 * 1024, windowsHide: true,
49
+ }).catch((error: unknown) => {
39
50
  if (error && typeof error === 'object' && 'stdout' in error && typeof error.stdout === 'string') {
40
51
  const failed = z.object({ ok: z.literal(false), error: z.object({ code: z.string() }) });
41
52
  const reply = failed.safeParse(JSON.parse(error.stdout || 'null'));
@@ -17,7 +17,7 @@ const webUrl = z.url({ protocol: /^https?$/ });
17
17
  export const dispatchPayloadSchema = z.strictObject({
18
18
  schemaVersion: z.literal(1),
19
19
  dispatchId: dispatchIdSchema,
20
- host: z.enum(['orca', 'helpra-works', 'local-cli', 'remote-webhook']),
20
+ host: z.enum(['orca', 'desktop', 'local-cli', 'remote-webhook']),
21
21
  targetAgentId: z.string().min(1).max(200),
22
22
  project: z.strictObject({ projectId: idSchema, workingCopyId: idSchema, name: z.string(), contentRevision: z.string() }),
23
23
  artboard: z.strictObject({
@@ -34,14 +34,20 @@ function unavailable(): DesignError { return new DesignError('service_unavailabl
34
34
 
35
35
  async function syncDirectory(directory: string): Promise<void> { const handle = await open(directory, 'r'); try { await handle.sync(); } finally { await handle.close(); } }
36
36
  async function safeRead(filename: string, limit: number): Promise<Buffer> {
37
- const handle = await open(filename, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
38
- try {
39
- const info = await handle.stat();
40
- if (!info.isFile() || info.nlink !== 1 || info.size > limit || info.uid !== process.getuid?.() || (info.mode & 0o077) !== 0) throw unavailable();
41
- const bytes = await handle.readFile();
42
- if (bytes.length !== info.size) throw unavailable();
43
- return bytes;
44
- } finally { await handle.close(); }
37
+ for (let attempt = 0; attempt < 3; attempt++) {
38
+ const handle = await open(filename, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
39
+ try {
40
+ const info = await handle.stat();
41
+ if (!info.isFile() || info.size > limit || info.uid !== process.getuid?.() || (info.mode & 0o077) !== 0) throw unavailable();
42
+ // An atomic replacement can unlink the file between open and stat.
43
+ if (info.nlink === 0) continue;
44
+ if (info.nlink !== 1) throw unavailable();
45
+ const bytes = await handle.readFile();
46
+ if (bytes.length !== info.size) throw unavailable();
47
+ return bytes;
48
+ } finally { await handle.close(); }
49
+ }
50
+ throw unavailable();
45
51
  }
46
52
 
47
53
  export class SourceExportJobStore {
@@ -13,46 +13,15 @@ export interface ResolvedCanvasScene {
13
13
  }
14
14
 
15
15
  const CANONICAL_DESIGN_PROJECT_IDS = new Set([
16
- "project-helpra-design-catalog",
16
+ "project-helpra-design-demo",
17
17
  ]);
18
18
  const CANONICAL_DESIGN_CANVAS_IDS = new Set([
19
19
  "canvas-helpra-design",
20
20
  ]);
21
21
 
22
- const CANONICAL_WORKS_PROJECT_IDS = new Set([
23
- "project-helpra-works-catalog",
24
- ]);
25
- const CANONICAL_WORKS_CANVAS_IDS = new Set([
26
- "canvas-mvp3",
27
- "canvas-5b56d6f2e526cf9d40a4",
28
- "canvas-0afd6f7fb298711b859b",
29
- "canvas-898ae39795540025c2a9",
30
- ]);
31
-
32
- const CANONICAL_BUSINESS_PROJECT_IDS = new Set([
33
- "project-efd0ea9e-eb78-4334-a3c1-9cbb01a088d9",
34
- ]);
35
- const CANONICAL_BUSINESS_CANVAS_IDS = new Set([
36
- "canvas-8ef744b86c3c358292de",
37
- "canvas-analytics",
38
- "canvas-01fce522bddfaf7cf9b0",
39
- "canvas-af950bef681e3294c97e",
40
- "canvas-3ab1f047c6132c7dbfe3",
41
- "canvas-ebcf98273563c11a00f6",
42
- "canvas-24f30b6dcfd82956d0a9",
43
- "canvas-cd6718e5647ac2b56d1d",
44
- "canvas-d5fc873188953b8270ac",
45
- "canvas-19085a908e3bbe792f62",
46
- "canvas-688597571b68705c6629",
47
- "canvas-ab9ef602a179090fad7d",
48
- "canvas-d96600cee38fb398757d",
49
- "canvas-5a8cddf53197fa2ac2b2",
50
- "canvas-ce7b4d38961770d7c0d1",
51
- ]);
52
-
53
22
  function sceneByKeywords(text: string): ResolvedCanvasScene | null {
54
23
  const normalized = text.toLowerCase();
55
- const isWorks = /(?:^|[^a-z0-9])(works|mvp[-_\s]?3)(?:$|[^a-z0-9])/.test(normalized);
24
+ const isWorks = /(?:^|[^a-z0-9])(works|workspace)(?:$|[^a-z0-9])/.test(normalized);
56
25
  const isBusiness = /(?:^|[^a-z0-9а-яё])(business|админ[а-яё]*|admin)(?:$|[^a-z0-9а-яё])/.test(normalized);
57
26
  const isDesign = /helpra[-_\s]+design/.test(normalized);
58
27
 
@@ -65,39 +34,26 @@ function sceneByKeywords(text: string): ResolvedCanvasScene | null {
65
34
  export function resolveCanvasScene(
66
35
  item: Pick<RecentCanvasItem, "workingCopyId" | "projectId" | "canvasId" | "projectName" | "canvasName">,
67
36
  ): ResolvedCanvasScene {
68
- // 1. Canonical stable IDs take strict priority so renaming a project or canvas never alters its scene.
37
+ // The built-in design scene takes priority over keyword matching.
69
38
  if (
70
39
  CANONICAL_DESIGN_PROJECT_IDS.has(item.projectId) ||
71
40
  CANONICAL_DESIGN_CANVAS_IDS.has(item.canvasId)
72
41
  ) {
73
42
  return { scene: "design" };
74
43
  }
75
- if (
76
- CANONICAL_WORKS_PROJECT_IDS.has(item.projectId) ||
77
- CANONICAL_WORKS_CANVAS_IDS.has(item.canvasId)
78
- ) {
79
- return { scene: "works", theme: "dark" };
80
- }
81
- if (
82
- CANONICAL_BUSINESS_PROJECT_IDS.has(item.projectId) ||
83
- CANONICAL_BUSINESS_CANVAS_IDS.has(item.canvasId)
84
- ) {
85
- return { scene: "business", theme: "light" };
86
- }
87
-
88
- // 2. Stable ID slugs before mutable display names.
89
- const stableIds = `${item.projectId} ${item.canvasId} ${item.workingCopyId}`;
90
- const byIdSlug = sceneByKeywords(stableIds);
44
+ // Project and canvas IDs survive renames.
45
+ const byIdSlug = sceneByKeywords(`${item.projectId} ${item.canvasId}`);
91
46
  if (byIdSlug) return byIdSlug;
92
47
  if (/(?:^|[^a-z0-9])design(?:$|[^a-z0-9])/i.test(item.projectId)) {
93
48
  return { scene: "design" };
94
49
  }
95
50
 
96
- // 3. Display-name fallback only for unknown IDs.
51
+ const byWorkingCopy = sceneByKeywords(item.workingCopyId);
52
+ if (byWorkingCopy) return byWorkingCopy;
97
53
  const byName = sceneByKeywords(`${item.projectName} ${item.canvasName}`);
98
54
  if (byName) return byName;
99
55
 
100
- // 4. Deterministic hash over stable IDs for arbitrary projects.
56
+ // Assign a stable scene to projects with no recognized keywords.
101
57
  let hash = 0;
102
58
  const seed = `${item.projectId}:${item.canvasId}`;
103
59
  for (let i = 0; i < seed.length; i += 1) hash = (hash * 31 + seed.charCodeAt(i)) | 0;