@things-factory/ai-assistant 10.1.6

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 (164) hide show
  1. package/client/components/board-ai-chat.test.ts +149 -0
  2. package/client/components/board-ai-chat.ts +3228 -0
  3. package/client/components/chat-defaults.ts +27 -0
  4. package/client/components/chat-echo-dedup.test.ts +230 -0
  5. package/client/components/chat-echo-dedup.ts +155 -0
  6. package/client/components/chat-input-builder.ts +69 -0
  7. package/client/components/markdown.test.ts +518 -0
  8. package/client/components/markdown.ts +508 -0
  9. package/client/components/mention-popup-helpers.ts +433 -0
  10. package/client/components/mention-popup.test.ts +588 -0
  11. package/client/components/mention-popup.ts +238 -0
  12. package/client/index.ts +14 -0
  13. package/client/tsconfig.json +13 -0
  14. package/client/utils/board-edit-patch.ts +374 -0
  15. package/dist-client/components/board-ai-chat.d.ts +423 -0
  16. package/dist-client/components/board-ai-chat.js +3034 -0
  17. package/dist-client/components/board-ai-chat.js.map +1 -0
  18. package/dist-client/components/board-ai-chat.test.d.ts +1 -0
  19. package/dist-client/components/board-ai-chat.test.js +138 -0
  20. package/dist-client/components/board-ai-chat.test.js.map +1 -0
  21. package/dist-client/components/chat-defaults.d.ts +8 -0
  22. package/dist-client/components/chat-defaults.js +22 -0
  23. package/dist-client/components/chat-defaults.js.map +1 -0
  24. package/dist-client/components/chat-echo-dedup.d.ts +54 -0
  25. package/dist-client/components/chat-echo-dedup.js +115 -0
  26. package/dist-client/components/chat-echo-dedup.js.map +1 -0
  27. package/dist-client/components/chat-echo-dedup.test.d.ts +1 -0
  28. package/dist-client/components/chat-echo-dedup.test.js +203 -0
  29. package/dist-client/components/chat-echo-dedup.test.js.map +1 -0
  30. package/dist-client/components/chat-input-builder.d.ts +55 -0
  31. package/dist-client/components/chat-input-builder.js +32 -0
  32. package/dist-client/components/chat-input-builder.js.map +1 -0
  33. package/dist-client/components/markdown.d.ts +60 -0
  34. package/dist-client/components/markdown.js +422 -0
  35. package/dist-client/components/markdown.js.map +1 -0
  36. package/dist-client/components/markdown.test.d.ts +1 -0
  37. package/dist-client/components/markdown.test.js +418 -0
  38. package/dist-client/components/markdown.test.js.map +1 -0
  39. package/dist-client/components/mention-popup-helpers.d.ts +165 -0
  40. package/dist-client/components/mention-popup-helpers.js +330 -0
  41. package/dist-client/components/mention-popup-helpers.js.map +1 -0
  42. package/dist-client/components/mention-popup.d.ts +35 -0
  43. package/dist-client/components/mention-popup.js +223 -0
  44. package/dist-client/components/mention-popup.js.map +1 -0
  45. package/dist-client/components/mention-popup.test.d.ts +1 -0
  46. package/dist-client/components/mention-popup.test.js +474 -0
  47. package/dist-client/components/mention-popup.test.js.map +1 -0
  48. package/dist-client/index.d.ts +14 -0
  49. package/dist-client/index.js +15 -0
  50. package/dist-client/index.js.map +1 -0
  51. package/dist-client/tsconfig.tsbuildinfo +1 -0
  52. package/dist-client/utils/board-edit-patch.d.ts +157 -0
  53. package/dist-client/utils/board-edit-patch.js +284 -0
  54. package/dist-client/utils/board-edit-patch.js.map +1 -0
  55. package/dist-server/index.d.ts +28 -0
  56. package/dist-server/index.js +32 -0
  57. package/dist-server/index.js.map +1 -0
  58. package/dist-server/service/chat-message/chat-message-broadcast.d.ts +13 -0
  59. package/dist-server/service/chat-message/chat-message-broadcast.js +13 -0
  60. package/dist-server/service/chat-message/chat-message-broadcast.js.map +1 -0
  61. package/dist-server/service/chat-message/chat-message-publish.d.ts +6 -0
  62. package/dist-server/service/chat-message/chat-message-publish.js +27 -0
  63. package/dist-server/service/chat-message/chat-message-publish.js.map +1 -0
  64. package/dist-server/service/chat-message/chat-message-subscription.d.ts +8 -0
  65. package/dist-server/service/chat-message/chat-message-subscription.js +57 -0
  66. package/dist-server/service/chat-message/chat-message-subscription.js.map +1 -0
  67. package/dist-server/service/chat-message/chat-message.d.ts +68 -0
  68. package/dist-server/service/chat-message/chat-message.js +172 -0
  69. package/dist-server/service/chat-message/chat-message.js.map +1 -0
  70. package/dist-server/service/chat-message/fold-history.d.ts +43 -0
  71. package/dist-server/service/chat-message/fold-history.js +33 -0
  72. package/dist-server/service/chat-message/fold-history.js.map +1 -0
  73. package/dist-server/service/chat-message/history-summary.d.ts +43 -0
  74. package/dist-server/service/chat-message/history-summary.js +77 -0
  75. package/dist-server/service/chat-message/history-summary.js.map +1 -0
  76. package/dist-server/service/chat-message/index.d.ts +5 -0
  77. package/dist-server/service/chat-message/index.js +12 -0
  78. package/dist-server/service/chat-message/index.js.map +1 -0
  79. package/dist-server/service/chat-message/llm-history.d.ts +46 -0
  80. package/dist-server/service/chat-message/llm-history.js +87 -0
  81. package/dist-server/service/chat-message/llm-history.js.map +1 -0
  82. package/dist-server/service/chat-session/chat-session.d.ts +60 -0
  83. package/dist-server/service/chat-session/chat-session.js +159 -0
  84. package/dist-server/service/chat-session/chat-session.js.map +1 -0
  85. package/dist-server/service/chat-session/index.d.ts +3 -0
  86. package/dist-server/service/chat-session/index.js +7 -0
  87. package/dist-server/service/chat-session/index.js.map +1 -0
  88. package/dist-server/service/chat-session/session-activity-broadcast.d.ts +30 -0
  89. package/dist-server/service/chat-session/session-activity-broadcast.js +34 -0
  90. package/dist-server/service/chat-session/session-activity-broadcast.js.map +1 -0
  91. package/dist-server/service/chat-session/session-activity-publish.d.ts +12 -0
  92. package/dist-server/service/chat-session/session-activity-publish.js +37 -0
  93. package/dist-server/service/chat-session/session-activity-publish.js.map +1 -0
  94. package/dist-server/service/chat-session/session-activity-subscription.d.ts +14 -0
  95. package/dist-server/service/chat-session/session-activity-subscription.js +87 -0
  96. package/dist-server/service/chat-session/session-activity-subscription.js.map +1 -0
  97. package/dist-server/service/chat-session/session-anchor.d.ts +26 -0
  98. package/dist-server/service/chat-session/session-anchor.js +100 -0
  99. package/dist-server/service/chat-session/session-anchor.js.map +1 -0
  100. package/dist-server/service/chat-session/session-inbox.d.ts +80 -0
  101. package/dist-server/service/chat-session/session-inbox.js +133 -0
  102. package/dist-server/service/chat-session/session-inbox.js.map +1 -0
  103. package/dist-server/service/chat-session-participant/chat-session-participant.d.ts +49 -0
  104. package/dist-server/service/chat-session-participant/chat-session-participant.js +141 -0
  105. package/dist-server/service/chat-session-participant/chat-session-participant.js.map +1 -0
  106. package/dist-server/service/chat-session-participant/index.d.ts +4 -0
  107. package/dist-server/service/chat-session-participant/index.js +10 -0
  108. package/dist-server/service/chat-session-participant/index.js.map +1 -0
  109. package/dist-server/service/chat-session-participant/invite-notification.d.ts +27 -0
  110. package/dist-server/service/chat-session-participant/invite-notification.js +30 -0
  111. package/dist-server/service/chat-session-participant/invite-notification.js.map +1 -0
  112. package/dist-server/service/chat-session-participant/presence.d.ts +4 -0
  113. package/dist-server/service/chat-session-participant/presence.js +22 -0
  114. package/dist-server/service/chat-session-participant/presence.js.map +1 -0
  115. package/dist-server/service/chat-session-resolver.d.ts +93 -0
  116. package/dist-server/service/chat-session-resolver.js +706 -0
  117. package/dist-server/service/chat-session-resolver.js.map +1 -0
  118. package/dist-server/service/index.d.ts +24 -0
  119. package/dist-server/service/index.js +39 -0
  120. package/dist-server/service/index.js.map +1 -0
  121. package/dist-server/service/subscribe-auth.d.ts +14 -0
  122. package/dist-server/service/subscribe-auth.js +33 -0
  123. package/dist-server/service/subscribe-auth.js.map +1 -0
  124. package/dist-server/service/types.d.ts +5 -0
  125. package/dist-server/service/types.js +12 -0
  126. package/dist-server/service/types.js.map +1 -0
  127. package/dist-server/tsconfig.tsbuildinfo +1 -0
  128. package/package.json +48 -0
  129. package/server/index.ts +28 -0
  130. package/server/service/chat-message/chat-message-broadcast.integration.test.ts +73 -0
  131. package/server/service/chat-message/chat-message-broadcast.test.ts +40 -0
  132. package/server/service/chat-message/chat-message-broadcast.ts +27 -0
  133. package/server/service/chat-message/chat-message-publish.ts +22 -0
  134. package/server/service/chat-message/chat-message-subscription.ts +45 -0
  135. package/server/service/chat-message/chat-message.ts +195 -0
  136. package/server/service/chat-message/fold-history.test.ts +98 -0
  137. package/server/service/chat-message/fold-history.ts +77 -0
  138. package/server/service/chat-message/history-summary.test.ts +127 -0
  139. package/server/service/chat-message/history-summary.ts +100 -0
  140. package/server/service/chat-message/index.ts +12 -0
  141. package/server/service/chat-message/llm-history.test.ts +194 -0
  142. package/server/service/chat-message/llm-history.ts +163 -0
  143. package/server/service/chat-session/chat-session.ts +193 -0
  144. package/server/service/chat-session/index.ts +5 -0
  145. package/server/service/chat-session/session-activity-broadcast.ts +57 -0
  146. package/server/service/chat-session/session-activity-publish.ts +44 -0
  147. package/server/service/chat-session/session-activity-subscription.ts +67 -0
  148. package/server/service/chat-session/session-anchor.ts +106 -0
  149. package/server/service/chat-session/session-inbox.test.ts +185 -0
  150. package/server/service/chat-session/session-inbox.ts +161 -0
  151. package/server/service/chat-session-participant/chat-session-participant.ts +135 -0
  152. package/server/service/chat-session-participant/index.ts +6 -0
  153. package/server/service/chat-session-participant/invite-notification.test.ts +30 -0
  154. package/server/service/chat-session-participant/invite-notification.ts +48 -0
  155. package/server/service/chat-session-participant/presence.test.ts +39 -0
  156. package/server/service/chat-session-participant/presence.ts +21 -0
  157. package/server/service/chat-session-resolver.ts +644 -0
  158. package/server/service/index.ts +37 -0
  159. package/server/service/session-anchor.test.ts +133 -0
  160. package/server/service/subscribe-auth.test.ts +57 -0
  161. package/server/service/subscribe-auth.ts +34 -0
  162. package/server/service/types.ts +15 -0
  163. package/things-factory.config.js +1 -0
  164. package/tsconfig.json +9 -0
@@ -0,0 +1,644 @@
1
+ /**
2
+ * ChatSession lifecycle resolver — start/get/recordDirectPatch/revertPatch + 메시지·패치 페이징 query.
3
+ *
4
+ * 핵심: `recordDirectPatch` — 사용자가 모델러에서 직접 편집 시 클라이언트가 호출.
5
+ * 이게 PatchEntry(source:'user-direct') + system 메시지 자동 추가 → AI 가 모든 변경을 인지.
6
+ */
7
+ import { Resolver, Query, Mutation, Arg, Ctx, Directive, Int, ObjectType, Field, ID } from 'type-graphql'
8
+ import { GraphQLJSON } from 'graphql-scalars'
9
+ import { User } from '@things-factory/auth-base'
10
+ import { buildDomainUsersQueryBuilder } from '@things-factory/auth-base/dist-server/utils/get-domain-users.js'
11
+
12
+ import { getRepository } from '@things-factory/shell'
13
+ import { In } from 'typeorm'
14
+
15
+ import { ChatSession } from './chat-session/chat-session.js'
16
+ import { anchorColumns, anchorWhere } from './chat-session/session-anchor.js'
17
+ import { buildInbox, applyHidden, activityPatch, searchInbox, INBOX_SCAN_CAP } from './chat-session/session-inbox.js'
18
+ import { publishSessionActivity } from './chat-session/session-activity-publish.js'
19
+ import { ChatMessage } from './chat-message/chat-message.js'
20
+ import { ChatSessionParticipant } from './chat-session-participant/chat-session-participant.js'
21
+ import { publishChatMessage } from './chat-message/chat-message-publish.js'
22
+
23
+ @ObjectType({
24
+ description:
25
+ 'Session list entry for the inbox — a session plus this viewer\'s unread state. Ordered by recent activity so a user can find where to go back to.'
26
+ })
27
+ class ChatSessionInboxEntry {
28
+ @Field(type => ID, { nullable: true, description: 'Session id.' })
29
+ id?: string
30
+
31
+ @Field({ nullable: true, description: 'User-given session name (tab label).' })
32
+ name?: string
33
+
34
+ @Field({ nullable: true, description: "What the session is anchored to: 'board' | 'space' | 'instance' | 'none'." })
35
+ anchorType?: string
36
+
37
+ @Field({ nullable: true, description: 'Id of the anchored target.' })
38
+ anchorId?: string
39
+
40
+ @Field({ nullable: true, description: 'Connected board id (board-anchored sessions).' })
41
+ boardId?: string
42
+
43
+ @Field({ nullable: true, description: 'Timestamp of the last message (list ordering / unread comparison).' })
44
+ lastMessageAt?: Date
45
+
46
+ @Field({ nullable: true, description: 'Short preview of the last message.' })
47
+ lastMessagePreview?: string
48
+
49
+ @Field({ nullable: true, description: 'Session creation timestamp.' })
50
+ createdAt?: Date
51
+
52
+ @Field({ description: 'Whether this viewer has unread activity in the session.' })
53
+ unread!: boolean
54
+
55
+ @Field({ description: 'Whether this viewer is a participant of the session (non-participants get no unread state).' })
56
+ participant!: boolean
57
+
58
+ /* 삭제는 되돌릴 수 없으므로 **만든 사람**만 한다 — 클라이언트가 버튼을 보일지 판단하는 근거.
59
+ * (권한 판정은 서버가 다시 한다. 이 값은 UI 힌트일 뿐이다.) */
60
+ @Field({ description: 'Whether this viewer created the session — only the creator may delete it.' })
61
+ mine!: boolean
62
+
63
+ /* 숨김은 나에게만 적용되고 되돌릴 수 있다 — 필터를 켠 사용자가 무엇이 숨겨진 것인지 알아야 한다. */
64
+ @Field({ nullable: true, description: 'Whether this viewer hid the session from their own list (only returned when showHidden is on).' })
65
+ hidden?: boolean
66
+ }
67
+
68
+ @Resolver()
69
+ export class ChatSessionResolver {
70
+ @Query(() => ChatSession, { nullable: true, description: 'Get AI chat session by id.' })
71
+ @Directive('@privilege(category: "ai-assistant", privilege: "query", legacy: "board-ai")')
72
+ async chatSession(
73
+ @Arg('id') id: string,
74
+ @Ctx() context: ResolverContext
75
+ ): Promise<ChatSession | null> {
76
+ const { domain } = context.state
77
+ return (await getRepository(ChatSession).findOneBy({ id, domain: { id: domain.id } })) ?? null
78
+ }
79
+
80
+ @Query(() => [ChatSession], {
81
+ description:
82
+ 'List AI chat sessions anchored to a target (oldest first). Anchor decides the nature and the history boundary of the conversation: board = authoring, space = the site and the twins running there. Board anchor also matches legacy rows that only have boardId.'
83
+ })
84
+ @Directive('@privilege(category: "ai-assistant", privilege: "query", legacy: "board-ai")')
85
+ async chatSessionsByAnchor(
86
+ @Arg('anchorType') anchorType: string,
87
+ @Arg('anchorId') anchorId: string,
88
+ @Ctx() context: ResolverContext
89
+ ): Promise<ChatSession[]> {
90
+ const { domain } = context.state
91
+ return await getRepository(ChatSession).find({
92
+ where: anchorWhere(domain.id, anchorType, anchorId),
93
+ order: { createdAt: 'ASC' }
94
+ })
95
+ }
96
+
97
+ /**
98
+ * 받은편지함 — 앵커의 세션 목록 + 내 안 읽음 상태. 최근 활동순.
99
+ * 집계 쿼리를 쓰지 않는다: 세션의 비정규화된 lastMessageAt 과 내 참여자 lastReadAt 을 **값 비교**한다
100
+ * (5개 DB 드라이버 지원 때문에 group by/MAX 를 목록 경로에 두지 않는다).
101
+ */
102
+ @Query(() => [ChatSessionInboxEntry], {
103
+ description:
104
+ "List sessions anchored to a target with this viewer's unread state, most recent activity first. Supports free-text search over name and last preview, a mine-only filter, hidden inclusion, and paging. Uses the denormalized last-activity timestamp compared against the viewer's read point — no per-session aggregation."
105
+ })
106
+ @Directive('@privilege(category: "ai-assistant", privilege: "query", legacy: "board-ai")')
107
+ async chatSessionInbox(
108
+ @Arg('anchorType') anchorType: string,
109
+ @Arg('anchorId') anchorId: string,
110
+ @Ctx() context: ResolverContext,
111
+ /* 숨긴 대화 보기 — 숨김이 한 번 넣으면 못 꺼내는 함정이 되지 않도록 필터를 준다. */
112
+ @Arg('showHidden', { nullable: true }) showHidden?: boolean,
113
+ /* 대량 목록 대응 — 검색·소유 필터·페이지. 목록 UI 는 처음부터 이걸 갖고 있어야 한다. */
114
+ @Arg('search', { nullable: true }) search?: string,
115
+ @Arg('mineOnly', { nullable: true }) mineOnly?: boolean,
116
+ @Arg('limit', () => Int, { nullable: true }) limit?: number,
117
+ @Arg('offset', () => Int, { nullable: true }) offset?: number
118
+ ): Promise<ChatSessionInboxEntry[]> {
119
+ const filtered = await this._inboxFiltered(anchorType, anchorId, context, { showHidden, search, mineOnly })
120
+ const from = Math.max(0, offset ?? 0)
121
+ const size = Math.min(Math.max(1, limit ?? 50), 200)
122
+ return filtered.slice(from, from + size) as any
123
+ }
124
+
125
+ /**
126
+ * 필터를 통과한 **전체 개수** — "더 보기" 가 남았는지, 검색 결과가 몇 건인지.
127
+ *
128
+ * 목록과 같은 요청에 담아 가져가므로 왕복은 늘지 않는다. 개수를 모르면 사용자는 목록의 끝이
129
+ * 페이지의 끝인지 자료의 끝인지 구별할 수 없다.
130
+ */
131
+ @Query(() => Int, {
132
+ description:
133
+ 'Total number of sessions matching the same filters as chatSessionInbox (before paging). Request it alongside the list so the UI can tell "end of page" from "end of data".'
134
+ })
135
+ @Directive('@privilege(category: "ai-assistant", privilege: "query", legacy: "board-ai")')
136
+ async chatSessionInboxTotal(
137
+ @Arg('anchorType') anchorType: string,
138
+ @Arg('anchorId') anchorId: string,
139
+ @Ctx() context: ResolverContext,
140
+ @Arg('showHidden', { nullable: true }) showHidden?: boolean,
141
+ @Arg('search', { nullable: true }) search?: string,
142
+ @Arg('mineOnly', { nullable: true }) mineOnly?: boolean
143
+ ): Promise<number> {
144
+ return (await this._inboxFiltered(anchorType, anchorId, context, { showHidden, search, mineOnly })).length
145
+ }
146
+
147
+ /** 필터 적용(페이지 전) — 목록·개수가 **같은 규칙**을 쓰도록 한 곳에 둔다(어긋나면 "더 보기" 가 거짓말이 된다). */
148
+ private async _inboxFiltered(
149
+ anchorType: string,
150
+ anchorId: string,
151
+ context: ResolverContext,
152
+ opts: { showHidden?: boolean; search?: string; mineOnly?: boolean }
153
+ ): Promise<ChatSessionInboxEntry[]> {
154
+ const all = await this._inboxEntries(anchorType, anchorId, context)
155
+ let entries = opts.showHidden ? all : all.filter(e => !e.hidden)
156
+ if (opts.mineOnly) entries = entries.filter(e => (e as any).mine)
157
+ return searchInbox(entries as any, opts.search) as any
158
+ }
159
+
160
+ /**
161
+ * 내가 숨긴 대화 수 — 필터에 "몇 개가 접혀 있는지" 를 보여주기 위한 값.
162
+ *
163
+ * 숨긴 것이 몇 개인지 모르면 필터를 눌러 볼 이유가 생기지 않는다(숨긴 사실 자체를 잊는다).
164
+ * 목록 조회와 **같은 요청**에 담아 가져갈 수 있으므로 왕복은 늘지 않는다.
165
+ */
166
+ @Query(() => Int, {
167
+ description:
168
+ "Number of sessions on this anchor that the caller has hidden and that have had no activity since. Meant to be requested alongside chatSessionInbox in the same operation so the filter can say how many are folded away."
169
+ })
170
+ @Directive('@privilege(category: "ai-assistant", privilege: "query", legacy: "board-ai")')
171
+ async hiddenSessionCount(
172
+ @Arg('anchorType') anchorType: string,
173
+ @Arg('anchorId') anchorId: string,
174
+ @Ctx() context: ResolverContext
175
+ ): Promise<number> {
176
+ const all = await this._inboxEntries(anchorType, anchorId, context)
177
+ return all.filter(e => e.hidden).length
178
+ }
179
+
180
+ /** 목록 조립 — 숨김 표시까지 붙인 **전체**. 목록·개수 두 진입점이 같은 규칙을 쓰도록 한 곳에 둔다. */
181
+ private async _inboxEntries(
182
+ anchorType: string,
183
+ anchorId: string,
184
+ context: ResolverContext
185
+ ): Promise<ChatSessionInboxEntry[]> {
186
+ const { domain, user } = context.state
187
+ /* 조회 상한 — 한 앵커의 대화가 아무리 늘어도 한 번에 이만큼만 훑는다. 최근 활동순으로 자른다
188
+ * (오래된 대화가 잘리는 것이 최근 대화가 잘리는 것보다 낫다). 정렬·검색·페이지는 순수 로직이 한다. */
189
+ const sessions = await getRepository(ChatSession).find({
190
+ where: anchorWhere(domain.id, anchorType, anchorId),
191
+ order: { lastMessageAt: 'DESC' },
192
+ take: INBOX_SCAN_CAP
193
+ })
194
+ if (sessions.length === 0) return []
195
+ const rows = await getRepository(ChatSessionParticipant).find({
196
+ where: { domain: { id: domain.id } as any, user: { id: user.id } as any, session: { id: In(sessions.map(s => s.id!)) } as any }
197
+ })
198
+ /* 'viewer' 는 대화에 낀 사람이 아니다 — 숨김을 기록하려고 만든 행이므로 읽음·안 읽음 판정에서 뺀다.
199
+ * (참여자가 아닌 사람에게 남의 협의 배지를 띄우지 않는다.) */
200
+ const participations = rows.filter(r => r.role !== 'viewer')
201
+ const hiddenAt = new Map(rows.map(r => [(r as any).sessionId as string, r.hiddenAt]))
202
+ /* 내가 만든 대화인지 표시 — 삭제 버튼을 보일지 결정하는 UI 힌트(권한은 서버가 다시 판정한다). */
203
+ const createdByMe = new Set(sessions.filter(s => (s as any).creatorId === user?.id).map(s => s.id))
204
+ const entries = buildInbox(sessions as any, participations as any).map(entry => ({
205
+ ...entry,
206
+ mine: createdByMe.has(entry.id)
207
+ }))
208
+ /* showHidden=true 로 불러 **전체**를 얻는다 — 숨김 여부 판정을 두 곳에 복제하지 않기 위함. */
209
+ return applyHidden(entries as any, hiddenAt, true) as any
210
+ }
211
+
212
+ /**
213
+ * 세션 삭제 — **만든 사람만.**
214
+ *
215
+ * 협의는 여럿의 기록이고 삭제는 화면에서 되돌릴 수 없다. 그래서 권한을 좁힌다(이름 변경은 되돌릴 수
216
+ * 있어서 누구나 할 수 있는 것과 대비). 권한이 없는 사람에게는 `hideAISession`(내 목록에서만 숨김)이
217
+ * 있다 — 남의 기록을 지우지 않고 자기 목록을 정리하는 길.
218
+ *
219
+ * 소프트 삭제(deletedAt)다 — 메시지·패치는 세션을 통해서만 도달하므로 함께 사라지고, 잘못 지운 경우
220
+ * 데이터로는 남아 있다. 다른 참여자 목록에서도 사라져야 하므로 meta 활동으로 방송한다.
221
+ */
222
+ @Mutation(() => Boolean, {
223
+ description:
224
+ 'Delete a chat session — creator only, since a shared deliberation cannot be un-deleted from the UI. Participants who are not the creator can hide it from their own list instead (hideAISession). Soft delete; broadcast as meta activity so every list drops it.'
225
+ })
226
+ @Directive('@privilege(category: "ai-assistant", privilege: "mutation", legacy: "board-ai")')
227
+ async deleteAISession(@Arg('sessionId') sessionId: string, @Ctx() context: ResolverContext): Promise<boolean> {
228
+ const { domain, user } = context.state
229
+ const repo = getRepository(ChatSession)
230
+ const session = await repo.findOneBy({ id: sessionId, domain: { id: domain.id } as any })
231
+ if (!session) return false
232
+ if (!user?.id || (session as any).creatorId !== user.id) {
233
+ /* 조용한 무동작이 아니라 명시 실패 — 지워진 줄 알고 넘어가면 안 된다. */
234
+ throw new Error('Only the user who created this session may delete it. Hide it from your own list instead.')
235
+ }
236
+ await repo.softDelete(sessionId)
237
+ publishSessionActivity({
238
+ domainId: domain.id,
239
+ sessionId,
240
+ kind: 'meta',
241
+ anchorType: (session as any).anchorType,
242
+ anchorId: (session as any).anchorId,
243
+ actorId: user?.id
244
+ })
245
+ return true
246
+ }
247
+
248
+ /**
249
+ * 내 목록에서 숨기기·되돌리기 — **나에게만** 적용된다(대화·다른 참여자 목록은 그대로).
250
+ *
251
+ * 참여자가 아니어도 숨길 수 있어야 한다 — 목록에는 같은 공간의 남의 협의도 보이고, 그것을 정리하는
252
+ * 것은 남에게 아무 영향이 없다. 그 경우 'viewer' 역할로 기록만 남긴다(참여자 명부·배지에는 들지 않는다).
253
+ */
254
+ @Mutation(() => Boolean, {
255
+ description:
256
+ 'Hide (or unhide) a session from the calling user\'s own list. Per-user and reversible — the session and other participants are unaffected. Activity newer than the hide makes it reappear; the inbox filter (showHidden) reveals hidden ones.'
257
+ })
258
+ @Directive('@privilege(category: "ai-assistant", privilege: "mutation", legacy: "board-ai")')
259
+ async hideAISession(
260
+ @Arg('sessionId') sessionId: string,
261
+ @Ctx() context: ResolverContext,
262
+ @Arg('hidden', { nullable: true }) hidden?: boolean
263
+ ): Promise<boolean> {
264
+ const { domain, user } = context.state
265
+ if (!user?.id) return false
266
+ const session = await getRepository(ChatSession).findOneBy({ id: sessionId, domain: { id: domain.id } as any })
267
+ if (!session) return false
268
+ const repo = getRepository(ChatSessionParticipant)
269
+ const existing = await repo.findOne({
270
+ where: { domain: { id: domain.id } as any, session: { id: sessionId } as any, user: { id: user.id } as any }
271
+ })
272
+ const hiddenAt = hidden === false ? null : new Date()
273
+ if (existing) {
274
+ await repo.update(existing.id!, { hiddenAt, updater: user } as any)
275
+ } else {
276
+ if (hidden === false) return true // 숨긴 적이 없으면 되돌릴 것도 없다
277
+ await repo.save({
278
+ domain: { id: domain.id } as any,
279
+ session: { id: sessionId } as any,
280
+ user: { id: user.id } as any,
281
+ role: 'viewer', // 대화에 낀 것이 아니라 숨김만 기록한다
282
+ hiddenAt,
283
+ creator: user,
284
+ updater: user
285
+ } as any)
286
+ }
287
+ return true
288
+ }
289
+
290
+ /**
291
+ * 세션 이름 변경 — **참여자 누구나** 할 수 있다.
292
+ *
293
+ * 왜 소유자 전용이 아닌가: 이름은 대화의 주제표이고 협의는 여럿이 한다. 논의가 흘러 주제가 달라졌는데
294
+ * 만든 사람만 고칠 수 있으면 그 사람이 없을 때 목록이 계속 어긋난다. 되돌릴 수 있는 변경이고 대화
295
+ * 내용에 영향이 없으므로 권한을 좁힐 이유가 없다(되돌릴 수 없는 것만 좁힌다).
296
+ *
297
+ * 변경은 **meta 활동**으로 방송한다 — 모든 참여자 목록에 즉시 반영되지만 안 읽음 배지는 올리지 않는다
298
+ * (이름 변경을 "새 소식" 으로 알리면 소음이다).
299
+ */
300
+ @Mutation(() => Boolean, {
301
+ description:
302
+ 'Rename a chat session. Any participant may rename it — the name is the topic label of a shared deliberation and the change is reversible. Broadcast as meta activity so every participant sees it without raising unread badges.'
303
+ })
304
+ @Directive('@privilege(category: "ai-assistant", privilege: "mutation", legacy: "board-ai")')
305
+ async renameAISession(
306
+ @Arg('sessionId') sessionId: string,
307
+ @Arg('name') name: string,
308
+ @Ctx() context: ResolverContext
309
+ ): Promise<boolean> {
310
+ const { domain, user } = context.state
311
+ const trimmed = (name ?? '').trim().slice(0, 200)
312
+ if (!trimmed) return false // 빈 이름으로 지우지 않는다 — 지우려면 별도 의도가 필요하다
313
+ const participant = await getRepository(ChatSessionParticipant).findOne({
314
+ where: { domain: { id: domain.id } as any, session: { id: sessionId } as any, user: { id: user.id } as any }
315
+ })
316
+ if (!participant) return false // 참여자가 아니면 남의 대화 제목을 바꿀 수 없다
317
+ const session = await getRepository(ChatSession).findOneBy({ id: sessionId, domain: { id: domain.id } as any })
318
+ if (!session) return false
319
+ await getRepository(ChatSession).update(sessionId, { name: trimmed, updater: user } as any)
320
+ publishSessionActivity({
321
+ domainId: domain.id,
322
+ sessionId,
323
+ kind: 'meta',
324
+ anchorType: (session as any).anchorType,
325
+ anchorId: (session as any).anchorId,
326
+ actorId: user?.id
327
+ })
328
+ return true
329
+ }
330
+
331
+ /**
332
+ * 읽은 지점 갱신 — 이 세션을 여기까지 읽었다. 멱등(여러 번 호출해도 최신 시각으로만 이동).
333
+ * 접속 표시(lastSeenAt)와 분리한다 — 창을 열어 두고 화면을 안 볼 수 있다.
334
+ */
335
+ @Mutation(() => Boolean, {
336
+ description:
337
+ "Mark a session as read up to now for the current user. Idempotent. Distinct from presence (lastSeenAt) — a window can be open without being read."
338
+ })
339
+ @Directive('@privilege(category: "ai-assistant", privilege: "mutation", legacy: "board-ai")')
340
+ async markSessionRead(
341
+ @Arg('sessionId') sessionId: string,
342
+ @Ctx() context: ResolverContext
343
+ ): Promise<boolean> {
344
+ const { domain, user } = context.state
345
+ const repo = getRepository(ChatSessionParticipant)
346
+ const mine = await repo.findOne({
347
+ where: { domain: { id: domain.id } as any, session: { id: sessionId } as any, user: { id: user.id } as any }
348
+ })
349
+ /* 참여자가 아니면 읽음 상태를 만들지 않는다 — 참여하지 않은 대화에 내 읽음 지점을 남기지 않는다. */
350
+ if (!mine) return false
351
+ await repo.update(mine.id!, { lastReadAt: new Date(), updater: user } as any)
352
+ return true
353
+ }
354
+
355
+ @Query(() => [User], {
356
+ description:
357
+ 'List users in the current domain for `@` mention popup. board-ai 권한이면 누구나 멘션용 검색 가능 (관리자 전용 users() 와 별도).'
358
+ })
359
+ @Directive('@privilege(category: "ai-assistant", privilege: "query", legacy: "board-ai")')
360
+ async domainUsersForMention(
361
+ @Arg('query', { nullable: true, description: 'Substring to match against name/email (case-insensitive). Empty → all.' }) query: string | undefined,
362
+ @Arg('limit', () => Int, { nullable: true, defaultValue: 50 }) limit: number,
363
+ @Ctx() context: ResolverContext
364
+ ): Promise<User[]> {
365
+ const { domain } = context.state
366
+ const qb = buildDomainUsersQueryBuilder(domain.id, 'USER')
367
+ if (query?.trim()) {
368
+ const q = `%${query.trim().toLowerCase()}%`
369
+ qb.andWhere('(LOWER(USER.name) LIKE :q OR LOWER(USER.email) LIKE :q)', { q })
370
+ }
371
+ qb.orderBy('USER.name', 'ASC').limit(limit)
372
+ return await qb.getMany()
373
+ }
374
+
375
+ @Query(() => [ChatSessionParticipant], {
376
+ description: 'List participants of a ChatSession (members / owner).'
377
+ })
378
+ @Directive('@privilege(category: "ai-assistant", privilege: "query", legacy: "board-ai")')
379
+ async chatSessionParticipants(
380
+ @Arg('sessionId') sessionId: string,
381
+ @Ctx() context: ResolverContext
382
+ ): Promise<ChatSessionParticipant[]> {
383
+ const { domain } = context.state
384
+ const session = await getRepository(ChatSession).findOneBy({
385
+ id: sessionId,
386
+ domain: { id: domain.id }
387
+ })
388
+ if (!session) return []
389
+ return await getRepository(ChatSessionParticipant).find({
390
+ where: { session: { id: sessionId } as any, domain: { id: domain.id } },
391
+ order: { createdAt: 'ASC' }
392
+ })
393
+ }
394
+
395
+ @Mutation(() => Boolean, {
396
+ description: 'Presence heartbeat — bump current user\'s lastSeenAt in the session (online indicator).'
397
+ })
398
+ @Directive('@privilege(category: "ai-assistant", privilege: "mutation", legacy: "board-ai")')
399
+ async touchPresence(@Arg('sessionId') sessionId: string, @Ctx() context: ResolverContext): Promise<boolean> {
400
+ const { domain, user } = context.state
401
+ const repo = getRepository(ChatSessionParticipant)
402
+ const part = await repo.findOne({
403
+ where: { session: { id: sessionId } as any, user: { id: user.id } as any, domain: { id: domain.id } as any }
404
+ })
405
+ if (!part) return false // 참여자가 아니면 heartbeat 무시 (초대 전)
406
+ await repo.update(part.id!, { lastSeenAt: new Date(), updater: user } as any)
407
+ return true
408
+ }
409
+
410
+ @Query(() => [ChatMessage], { description: 'List chat messages of a session, oldest first.' })
411
+ @Directive('@privilege(category: "ai-assistant", privilege: "query", legacy: "board-ai")')
412
+ async chatMessages(
413
+ @Arg('sessionId') sessionId: string,
414
+ @Arg('limit', () => Int, { nullable: true, defaultValue: 100 }) limit: number,
415
+ @Arg('offset', () => Int, { nullable: true, defaultValue: 0 }) offset: number,
416
+ @Ctx() context: ResolverContext
417
+ ): Promise<ChatMessage[]> {
418
+ const { domain } = context.state
419
+ const session = await getRepository(ChatSession).findOneBy({
420
+ id: sessionId,
421
+ domain: { id: domain.id }
422
+ })
423
+ if (!session) return []
424
+ return await getRepository(ChatMessage).find({
425
+ where: { session: { id: sessionId } as any },
426
+ // creator: 그룹챗 발신자 표시(name) + 자기 여부 판정(email). 내부 관리키(id)에 의존하지 않는다.
427
+ relations: { creator: true },
428
+ order: { createdAt: 'ASC' },
429
+ take: limit,
430
+ skip: offset
431
+ })
432
+ }
433
+
434
+ @Directive('@transaction')
435
+ @Mutation(() => ChatSession, {
436
+ description:
437
+ 'Start (or get existing) AI chat session anchored to a target. Idempotent — returns first existing or creates one. Use anchorType board for board authoring, space for a site (its co-located twins).'
438
+ })
439
+ @Directive('@privilege(category: "ai-assistant", privilege: "mutation", legacy: "board-ai")')
440
+ async startAISession(
441
+ @Arg('anchorType') anchorType: string,
442
+ @Arg('anchorId') anchorId: string,
443
+ @Ctx() context: ResolverContext
444
+ ): Promise<ChatSession> {
445
+ const { domain, user, tx } = context.state
446
+ const repo = getRepository(ChatSession, tx)
447
+
448
+ const existing = await repo.findOneBy(anchorWhere(domain.id, anchorType, anchorId))
449
+ if (existing) return existing
450
+
451
+ const session = await repo.save({
452
+ domain,
453
+ ...anchorColumns(anchorType, anchorId),
454
+ creator: user,
455
+ updater: user
456
+ } as any)
457
+ // creator 를 owner participant 로 자동 등록 — 다자간 채팅 기반.
458
+ await getRepository(ChatSessionParticipant, tx).save({
459
+ domain,
460
+ session: { id: session.id } as any,
461
+ user,
462
+ role: 'owner',
463
+ creator: user,
464
+ updater: user
465
+ } as any)
466
+ return session
467
+ }
468
+
469
+ @Directive('@transaction')
470
+ @Mutation(() => ChatSession, {
471
+ description:
472
+ 'Always create a new AI chat session anchored to a target (no idempotent reuse). For multi-session UX — 새 탭 열기.'
473
+ })
474
+ @Directive('@privilege(category: "ai-assistant", privilege: "mutation", legacy: "board-ai")')
475
+ async createAISession(
476
+ @Arg('anchorType') anchorType: string,
477
+ @Arg('anchorId') anchorId: string,
478
+ @Arg('name', { nullable: true, description: 'Optional name (defaults to auto-generated `세션 N`).' }) name: string | undefined,
479
+ @Ctx() context: ResolverContext
480
+ ): Promise<ChatSession> {
481
+ const { domain, user, tx } = context.state
482
+ const repo = getRepository(ChatSession, tx)
483
+
484
+ // 이름 미지정 시 자동 생성 — **같은 앵커**의 기존 세션 수 + 1.
485
+ let finalName = name?.trim()
486
+ if (!finalName) {
487
+ const count = await repo.count({ where: anchorWhere(domain.id, anchorType, anchorId) })
488
+ finalName = `세션 ${count + 1}`
489
+ }
490
+
491
+ const session = await repo.save({
492
+ domain,
493
+ ...anchorColumns(anchorType, anchorId),
494
+ creator: user,
495
+ updater: user,
496
+ name: finalName
497
+ } as any)
498
+ // creator 를 owner participant 로 자동 등록.
499
+ await getRepository(ChatSessionParticipant, tx).save({
500
+ domain,
501
+ session: { id: session.id } as any,
502
+ user,
503
+ role: 'owner',
504
+ creator: user,
505
+ updater: user
506
+ } as any)
507
+ return session
508
+ }
509
+
510
+ @Directive('@transaction')
511
+ @Mutation(() => Boolean, {
512
+ description: 'Rename a ChatSession (tab label).'
513
+ })
514
+ @Directive('@privilege(category: "ai-assistant", privilege: "mutation", legacy: "board-ai")')
515
+ async renameChatSession(
516
+ @Arg('sessionId') sessionId: string,
517
+ @Arg('name') name: string,
518
+ @Ctx() context: ResolverContext
519
+ ): Promise<boolean> {
520
+ const { domain, user, tx } = context.state
521
+ const repo = getRepository(ChatSession, tx)
522
+ const session = await repo.findOneBy({ id: sessionId, domain: { id: domain.id } })
523
+ if (!session) throw new Error(`ChatSession ${sessionId} not found`)
524
+ await repo.update(sessionId, { name: name.trim() || null, updater: user } as any)
525
+ return true
526
+ }
527
+
528
+ @Directive('@transaction')
529
+ @Mutation(() => Boolean, {
530
+ description:
531
+ 'Append a system note to a session — context that did not come from a participant typing (e.g. a conversation carried over from another surface, an external state change). The AI sees it as part of the shared history.'
532
+ })
533
+ @Directive('@privilege(category: "ai-assistant", privilege: "mutation", legacy: "board-ai")')
534
+ async appendSessionNote(
535
+ @Arg('sessionId') sessionId: string,
536
+ @Arg('content') content: string,
537
+ @Ctx() context: ResolverContext
538
+ ): Promise<boolean> {
539
+ const { domain, user, tx } = context.state
540
+ const session = await getRepository(ChatSession, tx).findOneBy({ id: sessionId, domain: { id: domain.id } })
541
+ if (!session) throw new Error(`ChatSession ${sessionId} not found`)
542
+ /* 프롬프트가 한 기록으로 폭증하지 않도록 자른다 — 맥락 전달이 목적이고 전문 보존이 아니다. */
543
+ const body = (content ?? '').trim().slice(0, 4000)
544
+ if (!body) return false
545
+
546
+ const previousLast = await getRepository(ChatMessage, tx).findOne({
547
+ where: { session: { id: session.id } as any },
548
+ order: { createdAt: 'DESC' }
549
+ })
550
+ const sysMsg = await getRepository(ChatMessage, tx).save({
551
+ session: { id: session.id } as any,
552
+ role: 'system',
553
+ content: body,
554
+ creator: user,
555
+ updater: user,
556
+ parentMessage: previousLast ? ({ id: previousLast.id } as any) : undefined
557
+ } as any)
558
+
559
+ /* 활동 갱신 + 방송 — 다른 참여자 목록·안 읽음과 열려 있는 화면의 transcript 일관성. best-effort. */
560
+ try {
561
+ await getRepository(ChatSession, tx).update(session.id!, activityPatch(body) as any)
562
+ } catch {
563
+ /* 기록 자체를 막지 않는다 */
564
+ }
565
+ publishSessionActivity({
566
+ domainId: domain.id,
567
+ sessionId: session.id!,
568
+ kind: 'message',
569
+ anchorType: (session as any).anchorType,
570
+ anchorId: (session as any).anchorId,
571
+ preview: body,
572
+ actorId: user?.id
573
+ })
574
+ publishChatMessage({ domainId: domain.id, sessionId: session.id, message: sysMsg })
575
+ return true
576
+ }
577
+
578
+ @Directive('@transaction')
579
+ @Mutation(() => Boolean, {
580
+ description:
581
+ 'Carry a conversation from another surface into this session as its own turns (user / assistant), preserving order. Use when a lightweight exchange is promoted into a persistent discussion — the participants should read it as the conversation continuing, not as a machine dump.'
582
+ })
583
+ @Directive('@privilege(category: "ai-assistant", privilege: "mutation", legacy: "board-ai")')
584
+ async appendSessionTurns(
585
+ @Arg('sessionId') sessionId: string,
586
+ @Arg('turns', () => GraphQLJSON) turns: { role?: string; content?: string }[],
587
+ @Ctx() context: ResolverContext
588
+ ): Promise<boolean> {
589
+ const { domain, user, tx } = context.state
590
+ const session = await getRepository(ChatSession, tx).findOneBy({ id: sessionId, domain: { id: domain.id } })
591
+ if (!session) throw new Error(`ChatSession ${sessionId} not found`)
592
+
593
+ /* 옮겨온 대화는 **그 대화의 발언 그대로** 들어간다 — 한 덩어리 기록으로 뭉치면 사람이 읽을 수 없고
594
+ * (화면 하나를 잡아먹는 이탤릭 덩어리), 마크다운도 죽는다. 대신 개수·길이는 제한한다: 맥락 전달이
595
+ * 목적이고 전문 보존이 아니다. */
596
+ const rows = (Array.isArray(turns) ? turns : [])
597
+ .map(t => ({
598
+ role: t?.role === 'ai' || t?.role === 'assistant' ? 'assistant' : t?.role === 'user' ? 'user' : 'system',
599
+ content: (t?.content ?? '').trim().slice(0, 4000)
600
+ }))
601
+ .filter(t => t.content)
602
+ .slice(-40)
603
+ if (!rows.length) return false
604
+
605
+ let previous = await getRepository(ChatMessage, tx).findOne({
606
+ where: { session: { id: session.id } as any },
607
+ order: { createdAt: 'DESC' }
608
+ })
609
+ const saved: ChatMessage[] = []
610
+ for (const row of rows) {
611
+ previous = await getRepository(ChatMessage, tx).save({
612
+ session: { id: session.id } as any,
613
+ role: row.role,
614
+ content: row.content,
615
+ creator: user,
616
+ updater: user,
617
+ parentMessage: previous ? ({ id: previous.id } as any) : undefined
618
+ } as any)
619
+ saved.push(previous!)
620
+ }
621
+
622
+ /* 활동은 마지막 발언 기준 한 번만 — 옮긴 줄마다 목록을 흔들 이유가 없다. */
623
+ const last = rows[rows.length - 1]
624
+ try {
625
+ await getRepository(ChatSession, tx).update(session.id!, activityPatch(last.content) as any)
626
+ } catch {
627
+ /* best-effort — 옮기기 자체를 막지 않는다 */
628
+ }
629
+ publishSessionActivity({
630
+ domainId: domain.id,
631
+ sessionId: session.id!,
632
+ kind: 'message',
633
+ anchorType: (session as any).anchorType,
634
+ anchorId: (session as any).anchorId,
635
+ preview: last.content,
636
+ actorId: user?.id
637
+ })
638
+ for (const message of saved) {
639
+ publishChatMessage({ domainId: domain.id, sessionId: session.id, message })
640
+ }
641
+ return true
642
+ }
643
+
644
+ }
@@ -0,0 +1,37 @@
1
+ import { ChatSessionResolver } from './chat-session-resolver.js'
2
+ import { MySessionActivitySubscription } from './chat-session/session-activity-subscription.js'
3
+ import { ChatMessageSubscription } from './chat-message/chat-message-subscription.js'
4
+ import { entities as ChatSessionEntities } from './chat-session/index.js'
5
+ import { entities as ChatMessageEntities } from './chat-message/index.js'
6
+ import { entities as ChatSessionParticipantEntities } from './chat-session-participant/index.js'
7
+
8
+ export * from './types.js'
9
+ export * from './chat-session-resolver.js'
10
+ export * from './subscribe-auth.js'
11
+ /* 앵커 순수 로직 — 호스트가 앵커 종류를 참조한다(리졸버는 데코레이터 때문에 무겁다). */
12
+ export * from './chat-session/session-anchor.js'
13
+ export * from './chat-session/index.js'
14
+ /* 순수 로직들 — 호스트(board-ai 등)가 같은 규칙을 쓰라고 공개한다. 베끼면 한쪽만 고쳐진다. */
15
+ export * from './chat-session/session-inbox.js'
16
+ export * from './chat-session/session-activity-publish.js'
17
+ export * from './chat-session/session-activity-broadcast.js'
18
+ export * from './chat-message/llm-history.js'
19
+ export * from './chat-message/history-summary.js'
20
+ export * from './chat-message/fold-history.js'
21
+ export * from './chat-message/chat-message-publish.js'
22
+ export * from './chat-message/chat-message-broadcast.js'
23
+ export * from './chat-session-participant/invite-notification.js'
24
+ export * from './chat-session-participant/presence.js'
25
+ export * from './chat-message/index.js'
26
+ export * from './chat-session-participant/index.js'
27
+
28
+ export const entities = [...ChatSessionEntities, ...ChatMessageEntities, ...ChatSessionParticipantEntities]
29
+
30
+ export const schema = {
31
+ resolverClasses: [
32
+ ChatSessionResolver,
33
+ ChatMessageSubscription,
34
+ /* 내가 참여한 모든 세션의 활동 — 창을 닫아 둔 표면이 배지·목록을 갱신할 수 있게. */
35
+ MySessionActivitySubscription
36
+ ]
37
+ }