@things-factory/ai-assistant 10.1.24 → 10.1.26
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.
- package/client/components/assistant-chat.ts +90 -18
- package/client/components/assistant-mode.test.ts +97 -0
- package/client/components/assistant-mode.ts +130 -0
- package/client/index.ts +1 -1
- package/dist-client/components/assistant-chat.d.ts +15 -4
- package/dist-client/components/assistant-chat.js +73 -18
- package/dist-client/components/assistant-chat.js.map +1 -1
- package/dist-client/components/assistant-mode.d.ts +97 -0
- package/dist-client/components/assistant-mode.js +36 -0
- package/dist-client/components/assistant-mode.js.map +1 -0
- package/dist-client/components/assistant-mode.test.d.ts +1 -0
- package/dist-client/components/assistant-mode.test.js +85 -0
- package/dist-client/components/assistant-mode.test.js.map +1 -0
- package/dist-client/index.d.ts +1 -1
- package/dist-client/index.js +1 -1
- package/dist-client/index.js.map +1 -1
- package/dist-client/tsconfig.tsbuildinfo +1 -1
- package/dist-server/index.d.ts +1 -0
- package/dist-server/index.js +1 -0
- package/dist-server/index.js.map +1 -1
- package/dist-server/service/assistant-chat-resolver.js +3 -1
- package/dist-server/service/assistant-chat-resolver.js.map +1 -1
- package/dist-server/service/index.d.ts +1 -0
- package/dist-server/service/index.js +1 -0
- package/dist-server/service/index.js.map +1 -1
- package/dist-server/service/tool-access.d.ts +4 -0
- package/dist-server/service/tool-access.js +23 -0
- package/dist-server/service/tool-access.js.map +1 -0
- package/dist-server/tool-registry-boot-report.d.ts +3 -0
- package/dist-server/tool-registry-boot-report.js +29 -0
- package/dist-server/tool-registry-boot-report.js.map +1 -0
- package/dist-server/tsconfig.tsbuildinfo +1 -1
- package/docs/session-controller.md +1 -1
- package/package.json +5 -5
- package/server/index.ts +1 -0
- package/server/service/assistant-chat-resolver.ts +3 -1
- package/server/service/index.ts +1 -0
- package/server/service/tool-access.test.ts +48 -0
- package/server/service/tool-access.ts +27 -0
- package/server/tool-registry-boot-report.test.ts +18 -0
- package/server/tool-registry-boot-report.ts +26 -0
- package/test/assistant-request-context.test.ts +2 -2
- package/test/assistant-session-controller.test.ts +0 -1
- package/test/assistant-session-toolbar.test.ts +2 -2
- package/client/utils/board-edit-patch.ts +0 -374
- package/dist-client/utils/board-edit-patch.d.ts +0 -157
- package/dist-client/utils/board-edit-patch.js +0 -284
- package/dist-client/utils/board-edit-patch.js.map +0 -1
|
@@ -41,7 +41,7 @@ Shared chat accepts synchronous `contextProvider(): {systemPrompt?, hostContext?
|
|
|
41
41
|
|
|
42
42
|
`autoAskRequestId` distinguishes repeated identical user requests; generate it per user submission, not per render. Without it, legacy text-based deduplication remains.
|
|
43
43
|
|
|
44
|
-
`
|
|
44
|
+
`scene-edit-patch` and `scene-action-execute` include local `detail.requestBase = {version: 1, sessionId, hostContext, modelFingerprint}`. `assistantModelFingerprint` returns a deterministic JSON signature, not a security hash. Undefined models have no signature. Hosts must validate target identity and compare the current model signature before applying a proposal. This metadata is not persisted into restored history; missing metadata is not proof that a historical proposal is safe. The framework captures the evidence but does not implement product-specific application guards.
|
|
45
45
|
|
|
46
46
|
Figure browser verification after toolbar migration: selected old session, reset to session 3, observed sessions 1 and 2 retained; screenshot confirmed aligned controls. Models were not edited. Plant runtime validation is owned by its development task. Legacy Board forwarding has source-contract coverage, not full Board browser coverage.
|
|
47
47
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@things-factory/ai-assistant",
|
|
3
|
-
"version": "10.1.
|
|
3
|
+
"version": "10.1.26",
|
|
4
4
|
"main": "dist-server/index.js",
|
|
5
5
|
"things-factory": true,
|
|
6
6
|
"author": "heartyoh",
|
|
@@ -29,10 +29,10 @@
|
|
|
29
29
|
"@operato/graphql": "^10.0.0",
|
|
30
30
|
"@operato/i18n": "^10.0.0",
|
|
31
31
|
"@operato/styles": "^10.0.0",
|
|
32
|
-
"@things-factory/ai-client-base": "^10.1.
|
|
33
|
-
"@things-factory/auth-base": "^10.1.
|
|
32
|
+
"@things-factory/ai-client-base": "^10.1.26",
|
|
33
|
+
"@things-factory/auth-base": "^10.1.26",
|
|
34
34
|
"@things-factory/env": "^10.1.20",
|
|
35
|
-
"@things-factory/shell": "^10.1.
|
|
35
|
+
"@things-factory/shell": "^10.1.26",
|
|
36
36
|
"dompurify": "^3.0.0",
|
|
37
37
|
"graphql-scalars": "^1.22.0",
|
|
38
38
|
"graphql-tag": "^2.12.6",
|
|
@@ -44,5 +44,5 @@
|
|
|
44
44
|
"copyfiles": "^2.4.1",
|
|
45
45
|
"rimraf": "^5.0.0"
|
|
46
46
|
},
|
|
47
|
-
"gitHead": "
|
|
47
|
+
"gitHead": "151bda14d899442c6846532ddded1e2bfe23a2f5"
|
|
48
48
|
}
|
package/server/index.ts
CHANGED
|
@@ -37,6 +37,7 @@ import { buildLlmHistory } from './chat-message/llm-history.js'
|
|
|
37
37
|
import { publishChatMessage } from './chat-message/chat-message-publish.js'
|
|
38
38
|
import { publishSessionActivity } from './chat-session/session-activity-publish.js'
|
|
39
39
|
import { activityPatch, autoSessionName } from './chat-session/session-inbox.js'
|
|
40
|
+
import { toolAccessFor } from './tool-access.js'
|
|
40
41
|
|
|
41
42
|
/**
|
|
42
43
|
* How many stored messages reach the model.
|
|
@@ -79,7 +80,7 @@ class AssistantChatInput {
|
|
|
79
80
|
@Field(() => [String], {
|
|
80
81
|
nullable: true,
|
|
81
82
|
description:
|
|
82
|
-
'Registered tool categories this conversation may use (registerToolCategory names, e.g. ["figure-authoring"]).
|
|
83
|
+
'Registered tool categories this conversation may use (registerToolCategory names, e.g. ["figure-authoring"]). Omitted or empty allows none — a plain conversation. A tool that declares a privilege is offered only to a caller who holds it.'
|
|
83
84
|
})
|
|
84
85
|
toolCategories?: string[]
|
|
85
86
|
|
|
@@ -292,6 +293,7 @@ export class AssistantChatResolver {
|
|
|
292
293
|
messages: conversation as any,
|
|
293
294
|
systemPrompt: input.systemPrompt,
|
|
294
295
|
toolCategories: input.toolCategories,
|
|
296
|
+
toolAccess: toolAccessFor(context),
|
|
295
297
|
hostContext: input.hostContext,
|
|
296
298
|
state: context.state,
|
|
297
299
|
model: input.model,
|
package/server/service/index.ts
CHANGED
|
@@ -9,6 +9,7 @@ import { entities as ChatSessionParticipantEntities } from './chat-session-parti
|
|
|
9
9
|
export * from './types.js'
|
|
10
10
|
export * from './chat-session-resolver.js'
|
|
11
11
|
export * from './assistant-chat-resolver.js'
|
|
12
|
+
export * from './tool-access.js'
|
|
12
13
|
export * from './subscribe-auth.js'
|
|
13
14
|
/* 앵커 순수 로직 — 호스트가 앵커 종류를 참조한다(리졸버는 데코레이터 때문에 무겁다). */
|
|
14
15
|
export * from './chat-session/session-anchor.js'
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* What this guards: a registered tool is asked the same question its GraphQL door asks.
|
|
3
|
+
*
|
|
4
|
+
* The tool declares `{ category, privilege }`; `@privilege` on the door runs `checkPermission`
|
|
5
|
+
* with the request's user, domain, address safety and prohibited list. If this passed fewer of
|
|
6
|
+
* those — say, dropped `unsafeIP` — the tool would be a softer way into the same door.
|
|
7
|
+
*/
|
|
8
|
+
const mockCheckPermission = jest.fn()
|
|
9
|
+
jest.mock('@things-factory/auth-base', () => ({ checkPermission: (...a: any[]) => mockCheckPermission(...a) }))
|
|
10
|
+
|
|
11
|
+
import { toolAccessFor } from './tool-access'
|
|
12
|
+
|
|
13
|
+
const state = {
|
|
14
|
+
domain: { id: 'dom-1' },
|
|
15
|
+
user: { id: 'u-1' },
|
|
16
|
+
unsafeIP: true,
|
|
17
|
+
prohibitedPrivileges: [{ category: 'board-import', privilege: 'mutation' }]
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
beforeEach(() => mockCheckPermission.mockReset())
|
|
21
|
+
|
|
22
|
+
it('★ asks checkPermission with the declared privilege and everything the door would pass', async () => {
|
|
23
|
+
mockCheckPermission.mockResolvedValue(true)
|
|
24
|
+
|
|
25
|
+
const allowed = await toolAccessFor({ state })({ category: 'board-import', privilege: 'mutation', owner: true })
|
|
26
|
+
|
|
27
|
+
expect(allowed).toBe(true)
|
|
28
|
+
expect(mockCheckPermission).toHaveBeenCalledWith(
|
|
29
|
+
{ category: 'board-import', privilege: 'mutation', owner: true, super: undefined },
|
|
30
|
+
state.user,
|
|
31
|
+
state.domain,
|
|
32
|
+
true,
|
|
33
|
+
state.prohibitedPrivileges
|
|
34
|
+
)
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
it('a refusal is a refusal', async () => {
|
|
38
|
+
mockCheckPermission.mockResolvedValue(false)
|
|
39
|
+
expect(await toolAccessFor({ state })({ category: 'board-import', privilege: 'query' })).toBe(false)
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
it('★ a request with no user or no domain holds no privilege, and auth is not asked', async () => {
|
|
43
|
+
const privilege = { category: 'board-import', privilege: 'query' }
|
|
44
|
+
expect(await toolAccessFor({ state: { domain: state.domain } })(privilege)).toBe(false)
|
|
45
|
+
expect(await toolAccessFor({ state: { user: state.user } })(privilege)).toBe(false)
|
|
46
|
+
expect(await toolAccessFor(undefined)(privilege)).toBe(false)
|
|
47
|
+
expect(mockCheckPermission).not.toHaveBeenCalled()
|
|
48
|
+
})
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Who may use a registered tool — the request's answer to `ToolAccessCheck`.
|
|
3
|
+
*
|
|
4
|
+
* `ai-client-base` decides *which* tools a conversation may use but does not know auth, so the
|
|
5
|
+
* conversation doors hand it this. A tool declares the same `{ category, privilege }` its GraphQL
|
|
6
|
+
* door uses (A1, 2026-09-17), and this asks exactly what `@privilege` on that door would ask: the
|
|
7
|
+
* same `checkPermission`, with the request's user, domain, address safety and prohibited list.
|
|
8
|
+
* Asking anything looser here would make the tool a second, softer way into that door.
|
|
9
|
+
*/
|
|
10
|
+
import { checkPermission } from '@things-factory/auth-base'
|
|
11
|
+
import type { ToolAccessCheck, ToolPrivilege } from '@things-factory/ai-client-base'
|
|
12
|
+
|
|
13
|
+
export function toolAccessFor(context: { state?: any } | undefined): ToolAccessCheck {
|
|
14
|
+
const { domain, user, unsafeIP, prohibitedPrivileges } = context?.state ?? {}
|
|
15
|
+
|
|
16
|
+
return async (privilege: ToolPrivilege) => {
|
|
17
|
+
/* No caller, no answer — a request without a user or domain holds no privilege. */
|
|
18
|
+
if (!user || !domain) return false
|
|
19
|
+
return !!(await checkPermission(
|
|
20
|
+
{ category: privilege.category, privilege: privilege.privilege, owner: privilege.owner, super: privilege.super },
|
|
21
|
+
user,
|
|
22
|
+
domain,
|
|
23
|
+
unsafeIP,
|
|
24
|
+
prohibitedPrivileges
|
|
25
|
+
))
|
|
26
|
+
}
|
|
27
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
jest.mock('@things-factory/env', () => ({ logger: { warn: jest.fn() } }))
|
|
2
|
+
|
|
3
|
+
import { formatToolRegistryWarnings } from './tool-registry-boot-report'
|
|
4
|
+
|
|
5
|
+
it('★ groups the recorded omissions by code and names every tool', () => {
|
|
6
|
+
const lines = formatToolRegistryWarnings([
|
|
7
|
+
{ code: 'tool-privilege-undeclared', params: { category: 'twin-authoring', tool: 'bindTwinEntity', kind: 'write' }, message: '' },
|
|
8
|
+
{ code: 'tool-privilege-undeclared', params: { category: 'x-ops', tool: 'runThing', kind: 'external' }, message: '' }
|
|
9
|
+
])
|
|
10
|
+
|
|
11
|
+
expect(lines).toEqual([
|
|
12
|
+
'[ai-assistant] tool-privilege-undeclared ×2: twin-authoring/bindTwinEntity(write), x-ops/runThing(external)'
|
|
13
|
+
])
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
it('says nothing when every tool is declared', () => {
|
|
17
|
+
expect(formatToolRegistryWarnings([])).toEqual([])
|
|
18
|
+
})
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* At boot, say which registered tools are not yet what the tool contract requires (A1 stage one).
|
|
3
|
+
*
|
|
4
|
+
* Registration no longer refuses a tool that changes something without declaring its privilege —
|
|
5
|
+
* refusing would stop apps whose tools predate the field. The registry records each omission as a
|
|
6
|
+
* code instead. This prints that list once, after every module has registered, grouped by code,
|
|
7
|
+
* so the person starting the server sees which tools still need a declaration. When the list is
|
|
8
|
+
* empty across the apps, registration becomes a refusal and this report goes away.
|
|
9
|
+
*/
|
|
10
|
+
import { logger } from '@things-factory/env'
|
|
11
|
+
import { getToolRegistryWarnings, type ToolRegistryWarning } from '@things-factory/ai-client-base'
|
|
12
|
+
|
|
13
|
+
/** One line per code: the code, how many, and which tools. Empty when there is nothing to report. */
|
|
14
|
+
export function formatToolRegistryWarnings(warnings: ReadonlyArray<ToolRegistryWarning>): string[] {
|
|
15
|
+
const byCode = new Map<string, string[]>()
|
|
16
|
+
for (const warning of warnings) {
|
|
17
|
+
const tools = byCode.get(warning.code) ?? []
|
|
18
|
+
tools.push(`${warning.params.category}/${warning.params.tool}(${warning.params.kind})`)
|
|
19
|
+
byCode.set(warning.code, tools)
|
|
20
|
+
}
|
|
21
|
+
return [...byCode].map(([code, tools]) => `[ai-assistant] ${code} ×${tools.length}: ${tools.join(', ')}`)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
process.on('bootstrap-module-start' as any, () => {
|
|
25
|
+
for (const line of formatToolRegistryWarnings(getToolRegistryWarnings())) logger.warn(line)
|
|
26
|
+
})
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import assert from 'node:assert/strict'
|
|
2
|
-
import { test } from 'node:test'
|
|
3
2
|
import { readFileSync } from 'node:fs'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
4
|
import { assistantAutoAskKey, assistantModelFingerprint, assistantRecentSessions } from '../client/utils/assistant-request-context.ts'
|
|
5
5
|
|
|
6
6
|
test('model signature ignores object key order but detects nested edits and array order', () => {
|
|
@@ -21,7 +21,7 @@ test('recent tabs retain the selected older conversation without mutating the in
|
|
|
21
21
|
assert.deepEqual(assistantRecentSessions([], '', 5), [])
|
|
22
22
|
})
|
|
23
23
|
test('send captures current context before optimistic input and attaches request base to edit events', () => {
|
|
24
|
-
const chat = readFileSync(
|
|
24
|
+
const chat = readFileSync(join(__dirname, '../client/components/assistant-chat.ts'), 'utf8')
|
|
25
25
|
const send = chat.slice(chat.indexOf('private async send()'))
|
|
26
26
|
assert.ok(send.indexOf('this.contextProvider?.()') < send.indexOf('// optimistic'))
|
|
27
27
|
assert.match(send, /modelFingerprint: assistantModelFingerprint\(liveBoard\)/)
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import assert from 'node:assert/strict'
|
|
2
|
-
import { test } from 'node:test'
|
|
3
2
|
import { AssistantSessionController, type AssistantSession, type AssistantSessionTarget } from '../client/utils/assistant-session-controller.ts'
|
|
4
3
|
|
|
5
4
|
const target = (id: string, scope = 'user:domain'): AssistantSessionTarget => ({ scope, anchorType: 'figure', anchorId: id })
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import assert from 'node:assert/strict'
|
|
2
2
|
import { readFileSync } from 'node:fs'
|
|
3
|
-
import {
|
|
4
|
-
const read = (file: string) => readFileSync(
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
const read = (file: string) => readFileSync(join(__dirname, file), 'utf8')
|
|
5
5
|
const toolbar = read('../client/components/assistant-session-toolbar.ts')
|
|
6
6
|
test('toolbar emits domain-neutral intent and never calls persistence APIs', () => {
|
|
7
7
|
for (const event of ['assistant-session-select', 'assistant-session-reset', 'assistant-session-retry']) assert.ok(toolbar.includes(event))
|
|
@@ -1,374 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Client-side BoardEditPatch types + applier.
|
|
3
|
-
*
|
|
4
|
-
* NOTE: 동일 정의가 server/service/types.ts + apply-patch.ts 에 있음.
|
|
5
|
-
* client 번들이 server 코드를 import 하지 않도록 분리. 변경 시 양쪽 동기화 필요.
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* 컴포넌트 타깃팅은 항상 `refid` (things-scene universal numeric handle).
|
|
10
|
-
* `id` 는 데이터 바인딩 이름이며 unique 가 아니므로 targeting 에 사용하지 않는다.
|
|
11
|
-
*
|
|
12
|
-
* 보드는 최상위 부모 — 자체 속성 (fillStyle / width / height / name 등) 을 갖고,
|
|
13
|
-
* `modifyBoard` 로 변경. 자식 컴포넌트 변경 (`modify`) 와 분리.
|
|
14
|
-
*
|
|
15
|
-
* Phase 2 — Scene 조작 op (align/distribute/group/ungroup/zorder). model 차원
|
|
16
|
-
* 시뮬레이션은 noop 이고 things-scene API 가 정본.
|
|
17
|
-
*/
|
|
18
|
-
export type AlignDirection =
|
|
19
|
-
| 'left'
|
|
20
|
-
| 'right'
|
|
21
|
-
| 'center'
|
|
22
|
-
| 'top'
|
|
23
|
-
| 'middle'
|
|
24
|
-
| 'bottom'
|
|
25
|
-
|
|
26
|
-
export type DistributeAxis = 'horizontal' | 'vertical'
|
|
27
|
-
|
|
28
|
-
export type ZorderDirection = 'front' | 'back' | 'forward' | 'backward'
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* Sugar layout — `arrange` op 의 layout 종류.
|
|
32
|
-
* Server-side types.ts 의 ArrangeLayout 와 일치 — drift test 가 검증.
|
|
33
|
-
*/
|
|
34
|
-
export type ArrangeLayout =
|
|
35
|
-
| { type: 'grid'; cols: number; gap?: number; anchor?: { left: number; top: number } }
|
|
36
|
-
| {
|
|
37
|
-
type: 'row'
|
|
38
|
-
gap?: number
|
|
39
|
-
anchor?: { left: number; top: number }
|
|
40
|
-
align?: 'start' | 'center' | 'end'
|
|
41
|
-
}
|
|
42
|
-
| {
|
|
43
|
-
type: 'column'
|
|
44
|
-
gap?: number
|
|
45
|
-
anchor?: { left: number; top: number }
|
|
46
|
-
align?: 'start' | 'center' | 'end'
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
export type BoardEditOp =
|
|
50
|
-
| { op: 'add'; component: any }
|
|
51
|
-
| { op: 'remove'; refid: number }
|
|
52
|
-
| { op: 'modify'; refid: number; patch: any }
|
|
53
|
-
| { op: 'modifyBoard'; patch: any }
|
|
54
|
-
| { op: 'replace'; board: any }
|
|
55
|
-
| { op: 'align'; refids: number[]; direction: AlignDirection }
|
|
56
|
-
| { op: 'distribute'; refids: number[]; axis: DistributeAxis }
|
|
57
|
-
| { op: 'group'; refids: number[] }
|
|
58
|
-
| { op: 'ungroup'; refid: number }
|
|
59
|
-
| { op: 'zorder'; refid: number; direction: ZorderDirection }
|
|
60
|
-
| { op: 'arrange'; refids: number[]; layout: ArrangeLayout }
|
|
61
|
-
|
|
62
|
-
/**
|
|
63
|
-
* C-1 — Scene 조작 action (ephemeral). 모델 변경 X, undo 영향 X.
|
|
64
|
-
* 호스트가 board-action-execute 이벤트로 받아서 things-scene API 직접 호출.
|
|
65
|
-
*/
|
|
66
|
-
export type BoardActionOp =
|
|
67
|
-
| { action: 'selectComponents'; refids: number[] }
|
|
68
|
-
| { action: 'centerToComponent'; refid: number; animated?: boolean }
|
|
69
|
-
| { action: 'fitToView'; mode?: 'fit' | 'ratio' | 'width' | 'height' }
|
|
70
|
-
| { action: 'setSceneMode'; mode: 'edit' | 'view' }
|
|
71
|
-
| { action: 'highlightComponents'; refids: number[] }
|
|
72
|
-
|
|
73
|
-
export interface BoardEditPatch {
|
|
74
|
-
ops: BoardEditOp[]
|
|
75
|
-
summary: string
|
|
76
|
-
confidence: number
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
export interface PatchApplyReport {
|
|
80
|
-
/** 패치 적용 후 보드. 모든 op 가 noop 이어도 입력 그대로 반환. */
|
|
81
|
-
board: any
|
|
82
|
-
/** 실제로 보드를 바꾼 op 들. */
|
|
83
|
-
applied: BoardEditOp[]
|
|
84
|
-
/** id 매칭 실패 등으로 noop 이 된 op 들 — 호출자가 사용자에게 알릴 단서. */
|
|
85
|
-
missed: BoardEditOp[]
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
const EMPTY_BOARD = { width: 1000, height: 600, components: [] as any[] }
|
|
89
|
-
|
|
90
|
-
/**
|
|
91
|
-
* Patch 를 BoardModel 에 적용 (pure, board 를 mutate 하지 않음).
|
|
92
|
-
*/
|
|
93
|
-
export function applyBoardEditPatch(board: any | undefined, patch: BoardEditPatch): any {
|
|
94
|
-
return applyBoardEditPatchVerbose(board, patch).board
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/**
|
|
98
|
-
* Verbose 변형 — 각 op 의 적용 여부를 보고.
|
|
99
|
-
*
|
|
100
|
-
* `modify` 와 `remove` 는 id 가 보드에 없으면 silent no-op 이 된다. LLM 이 잘못된
|
|
101
|
-
* id 를 만들어 보내면 사용자에게 "수정했습니다" 라고 답하지만 실제로는 아무 변화도
|
|
102
|
-
* 없는 상황이 발생 — 호스트가 missed 를 보고 사용자에게 경고할 수 있도록 별도
|
|
103
|
-
* entry point 제공.
|
|
104
|
-
*/
|
|
105
|
-
export function applyBoardEditPatchVerbose(
|
|
106
|
-
board: any | undefined,
|
|
107
|
-
patch: BoardEditPatch
|
|
108
|
-
): PatchApplyReport {
|
|
109
|
-
let result: any = board ?? EMPTY_BOARD
|
|
110
|
-
const applied: BoardEditOp[] = []
|
|
111
|
-
const missed: BoardEditOp[] = []
|
|
112
|
-
|
|
113
|
-
for (const op of patch.ops) {
|
|
114
|
-
if (SCENE_ONLY_OPS.has(op.op)) {
|
|
115
|
-
// scene-only — model 차원 noop, scene 차원 적용. applied 분류.
|
|
116
|
-
applied.push(op)
|
|
117
|
-
continue
|
|
118
|
-
}
|
|
119
|
-
const next = applyOp(result, op)
|
|
120
|
-
// componentsUnchanged 는 components 배열 동일 + width/height/fillStyle 동일 만 본다.
|
|
121
|
-
// modify / remove 의 silent no-op (ghost refid) 검출 전용 — modifyBoard 가 sky
|
|
122
|
-
// 등 다른 root 키만 바꿀 때 false negative 로 missed 분류되는 회귀 방지.
|
|
123
|
-
const componentMutating = op.op === 'modify' || op.op === 'remove'
|
|
124
|
-
if (next === result || (componentMutating && componentsUnchanged(result, next))) {
|
|
125
|
-
missed.push(op)
|
|
126
|
-
} else {
|
|
127
|
-
applied.push(op)
|
|
128
|
-
result = next
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
return { board: result, applied, missed }
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
function componentsUnchanged(prev: any, next: any): boolean {
|
|
136
|
-
// applyOp 는 항상 새 객체를 만든다. 따라서 reference 비교가 안 되고 내용 비교 필요.
|
|
137
|
-
// components 는 map/filter 결과 reference 도 다를 수 있으므로 length + 요소 ref 비교.
|
|
138
|
-
const a = prev.components ?? []
|
|
139
|
-
const b = next.components ?? []
|
|
140
|
-
if (a.length !== b.length) return false
|
|
141
|
-
for (let i = 0; i < a.length; i++) {
|
|
142
|
-
if (a[i] !== b[i]) return false
|
|
143
|
-
}
|
|
144
|
-
return prev.width === next.width && prev.height === next.height && prev.fillStyle === next.fillStyle
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
const SCENE_ONLY_OPS = new Set<BoardEditOp['op']>([
|
|
148
|
-
'align',
|
|
149
|
-
'distribute',
|
|
150
|
-
'group',
|
|
151
|
-
'ungroup',
|
|
152
|
-
'zorder',
|
|
153
|
-
'arrange'
|
|
154
|
-
])
|
|
155
|
-
|
|
156
|
-
function applyOp(board: any, op: BoardEditOp): any {
|
|
157
|
-
switch (op.op) {
|
|
158
|
-
case 'replace':
|
|
159
|
-
return op.board
|
|
160
|
-
case 'add':
|
|
161
|
-
return { ...board, components: [...(board.components || []), op.component] }
|
|
162
|
-
case 'remove':
|
|
163
|
-
// 자식 (group/container 안) refid 도 매칭 — deep search.
|
|
164
|
-
return {
|
|
165
|
-
...board,
|
|
166
|
-
components: removeComponentDeep(board.components || [], op.refid)
|
|
167
|
-
}
|
|
168
|
-
case 'modify':
|
|
169
|
-
// 자식 refid 도 매칭 — group/container 안의 컴포넌트 수정 가능.
|
|
170
|
-
return {
|
|
171
|
-
...board,
|
|
172
|
-
components: modifyComponentDeep(board.components || [], op.refid, op.patch)
|
|
173
|
-
}
|
|
174
|
-
case 'modifyBoard': {
|
|
175
|
-
const patch = { ...(op.patch || {}) }
|
|
176
|
-
delete patch.components // 자식 변경은 별도 op
|
|
177
|
-
return mergeComponent(board, patch) // 최상위 board 자체에 deep-merge
|
|
178
|
-
}
|
|
179
|
-
case 'align':
|
|
180
|
-
case 'distribute':
|
|
181
|
-
case 'group':
|
|
182
|
-
case 'ungroup':
|
|
183
|
-
case 'zorder':
|
|
184
|
-
case 'arrange':
|
|
185
|
-
// scene-only — model 차원 noop. things-scene API 가 정본.
|
|
186
|
-
return board
|
|
187
|
-
default:
|
|
188
|
-
return board
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
/**
|
|
193
|
-
* 주어진 board 상태에서 op 의 inverse 를 계산.
|
|
194
|
-
*
|
|
195
|
-
* Revert 기능 — patch 적용 직전 board + op 로 역연산을 만든다. 호스트가
|
|
196
|
-
* 누적해두면 나중에 역순 실행만으로 복원.
|
|
197
|
-
*
|
|
198
|
-
* add 의 inverse 는 새로 발급될 refid 를 알아야 → 모델 단계에서 계산 불가.
|
|
199
|
-
* 호스트가 scene.add 직후 refid 를 캡처해 직접 만들 것.
|
|
200
|
-
*/
|
|
201
|
-
export function computeInverseOp(board: any, op: BoardEditOp): BoardEditOp | null {
|
|
202
|
-
if (!board) return null
|
|
203
|
-
const components = board.components ?? []
|
|
204
|
-
|
|
205
|
-
switch (op.op) {
|
|
206
|
-
case 'add':
|
|
207
|
-
return null
|
|
208
|
-
|
|
209
|
-
case 'remove': {
|
|
210
|
-
// 자식 refid 도 매칭 (deep search)
|
|
211
|
-
const target = findComponentDeep(components, op.refid)
|
|
212
|
-
if (!target) return null
|
|
213
|
-
return { op: 'add', component: JSON.parse(JSON.stringify(target)) }
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
case 'modify': {
|
|
217
|
-
// 자식 refid 도 매칭 (deep search)
|
|
218
|
-
const target = findComponentDeep(components, op.refid)
|
|
219
|
-
if (!target) return null
|
|
220
|
-
const oldValues: any = {}
|
|
221
|
-
for (const k of Object.keys(op.patch || {})) {
|
|
222
|
-
const v = (target as any)[k]
|
|
223
|
-
oldValues[k] = v === undefined ? null : JSON.parse(JSON.stringify(v))
|
|
224
|
-
}
|
|
225
|
-
return { op: 'modify', refid: op.refid, patch: oldValues }
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
case 'modifyBoard': {
|
|
229
|
-
const oldValues: any = {}
|
|
230
|
-
const patch = op.patch || {}
|
|
231
|
-
for (const k of Object.keys(patch)) {
|
|
232
|
-
if (k === 'components') continue
|
|
233
|
-
const v = (board as any)[k]
|
|
234
|
-
oldValues[k] = v === undefined ? null : JSON.parse(JSON.stringify(v))
|
|
235
|
-
}
|
|
236
|
-
return { op: 'modifyBoard', patch: oldValues }
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
case 'replace':
|
|
240
|
-
return { op: 'replace', board: JSON.parse(JSON.stringify(board)) }
|
|
241
|
-
|
|
242
|
-
case 'zorder': {
|
|
243
|
-
// forward ↔ backward / front ↔ back. front/back 의 inverse 는 정확하지
|
|
244
|
-
// 않을 수 있음 (best-effort) — 정확 inverse 는 호스트가 zorder 직전 index
|
|
245
|
-
// 를 캡처해서 명시 modify 시퀀스로 만들어야.
|
|
246
|
-
const opp: Record<string, 'front' | 'back' | 'forward' | 'backward'> = {
|
|
247
|
-
forward: 'backward',
|
|
248
|
-
backward: 'forward',
|
|
249
|
-
front: 'back',
|
|
250
|
-
back: 'front'
|
|
251
|
-
}
|
|
252
|
-
const dir = opp[op.direction]
|
|
253
|
-
if (!dir) return null
|
|
254
|
-
return { op: 'zorder', refid: op.refid, direction: dir }
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
case 'align':
|
|
258
|
-
case 'distribute':
|
|
259
|
-
case 'group':
|
|
260
|
-
case 'ungroup':
|
|
261
|
-
case 'arrange':
|
|
262
|
-
// scene 호출 후에야 변경 결과 알 수 있음. 호스트가 직접 inverse 만든다.
|
|
263
|
-
return null
|
|
264
|
-
|
|
265
|
-
default:
|
|
266
|
-
return null
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
/**
|
|
271
|
-
* 컴포넌트에 부분 patch 를 적용 (deep merge).
|
|
272
|
-
* threeD 등 nested object 는 deep merge — 색만 바꾸려고 했을 때 geometry 까지 사라지지 않도록.
|
|
273
|
-
*
|
|
274
|
-
* patch 내 `null` 의 시맨틱 — **"이 키를 제거하라"**:
|
|
275
|
-
* - fillStyle/strokeStyle 처럼 `string | object | undefined` 인 필드는 null 로
|
|
276
|
-
* set 하면 typeof null === 'object' 함정에 빠져 다운스트림 (3D 텍스처 등) 이 크래시.
|
|
277
|
-
* - computeInverseOp 가 base 에 키가 없던 (`undefined`) 경우 inverse 를 null 로
|
|
278
|
-
* 발급하므로, 이 시맨틱과 정확히 일치 — inverse 가 자연스럽게 올바로 동작.
|
|
279
|
-
*
|
|
280
|
-
* host (board-modeller-page) 에서 things-scene 의 component.set(merged) 호출 전에 사용.
|
|
281
|
-
*/
|
|
282
|
-
export function mergeComponent(base: any, patch: any): any {
|
|
283
|
-
const out: any = { ...base }
|
|
284
|
-
for (const key of Object.keys(patch)) {
|
|
285
|
-
const patchVal = patch[key]
|
|
286
|
-
if (patchVal === null) {
|
|
287
|
-
delete out[key]
|
|
288
|
-
} else if (isPlainObject(base[key]) && isPlainObject(patchVal)) {
|
|
289
|
-
out[key] = deepMerge(base[key], patchVal)
|
|
290
|
-
} else {
|
|
291
|
-
out[key] = patchVal
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
return out
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
function deepMerge(a: any, b: any): any {
|
|
298
|
-
const out: any = { ...a }
|
|
299
|
-
for (const key of Object.keys(b)) {
|
|
300
|
-
const bv = b[key]
|
|
301
|
-
if (bv === null) {
|
|
302
|
-
delete out[key]
|
|
303
|
-
} else if (isPlainObject(a[key]) && isPlainObject(bv)) {
|
|
304
|
-
out[key] = deepMerge(a[key], bv)
|
|
305
|
-
} else {
|
|
306
|
-
out[key] = bv
|
|
307
|
-
}
|
|
308
|
-
}
|
|
309
|
-
return out
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
function isPlainObject(v: any): boolean {
|
|
313
|
-
return v !== null && typeof v === 'object' && !Array.isArray(v)
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
// ── 자식 컴포넌트 (group/container 안) 까지 매칭 — deep search ─
|
|
317
|
-
// server/service/apply-patch.ts 와 동일 로직. drift test 가 동등성 보장.
|
|
318
|
-
|
|
319
|
-
function findComponentDeep(components: any[], refid: number): any | undefined {
|
|
320
|
-
for (const c of components) {
|
|
321
|
-
if (!c) continue
|
|
322
|
-
if (c.refid === refid) return c
|
|
323
|
-
if (Array.isArray(c.components) && c.components.length > 0) {
|
|
324
|
-
const sub = findComponentDeep(c.components, refid)
|
|
325
|
-
if (sub) return sub
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
return undefined
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
function modifyComponentDeep(components: any[], refid: number, patch: any): any[] {
|
|
332
|
-
let changed = false
|
|
333
|
-
const out = components.map(c => {
|
|
334
|
-
if (!c) return c
|
|
335
|
-
if (c.refid === refid) {
|
|
336
|
-
changed = true
|
|
337
|
-
return mergeComponent(c, patch)
|
|
338
|
-
}
|
|
339
|
-
if (Array.isArray(c.components) && c.components.length > 0) {
|
|
340
|
-
const updated = modifyComponentDeep(c.components, refid, patch)
|
|
341
|
-
if (updated !== c.components) {
|
|
342
|
-
changed = true
|
|
343
|
-
return { ...c, components: updated }
|
|
344
|
-
}
|
|
345
|
-
}
|
|
346
|
-
return c
|
|
347
|
-
})
|
|
348
|
-
return changed ? out : components
|
|
349
|
-
}
|
|
350
|
-
|
|
351
|
-
function removeComponentDeep(components: any[], refid: number): any[] {
|
|
352
|
-
let changed = false
|
|
353
|
-
const out: any[] = []
|
|
354
|
-
for (const c of components) {
|
|
355
|
-
if (!c) {
|
|
356
|
-
out.push(c)
|
|
357
|
-
continue
|
|
358
|
-
}
|
|
359
|
-
if (c.refid === refid) {
|
|
360
|
-
changed = true
|
|
361
|
-
continue
|
|
362
|
-
}
|
|
363
|
-
if (Array.isArray(c.components) && c.components.length > 0) {
|
|
364
|
-
const updated = removeComponentDeep(c.components, refid)
|
|
365
|
-
if (updated !== c.components) {
|
|
366
|
-
changed = true
|
|
367
|
-
out.push({ ...c, components: updated })
|
|
368
|
-
continue
|
|
369
|
-
}
|
|
370
|
-
}
|
|
371
|
-
out.push(c)
|
|
372
|
-
}
|
|
373
|
-
return changed ? out : components
|
|
374
|
-
}
|