Merge pull request #7 from shumaiOne/feat/agent-chat-context

feat(agent): add agent chat context session routing and thread support
This commit is contained in:
Yiling-J
2026-05-22 11:26:33 +08:00
committed by GitHub
19 changed files with 1043 additions and 252 deletions
+1 -1
View File
@@ -6,7 +6,7 @@ out
*.log
.env
.env.*
.pi/agents/
.pi/
data/
*.db
*.diff
+1
View File
@@ -297,6 +297,7 @@ We use a custom workflow engine that supports both **Local** (polling-based) and
- **Location**: Defined in `src/services/workflow/activities/<domain>.ts`.
- **Export**: Export individual activity functions and re-export them in `src/services/workflow/activities/index.ts`.
- **Implementation**: Activities _can_ and _should_ call other services (e.g., `aiService`, `transcodeService`) or interact with the database.
- **Database Access Restriction**: **Agent activities (or other non-database activities) are strictly prohibited from calling the database directly.** All database queries or updates must be isolated within dedicated database activities defined in `src/workflow/activities/db.ts` (running on `db_queue` / `TaskQueueDb`). Workflow functions coordinate execution by first invoking the database activity to resolve and store state, then passing the resolved data to the agent/non-database activity.
## Import conventions
@@ -0,0 +1,2 @@
-- DropIndex
DROP INDEX "asset_comments_session_id_key";
+2 -2
View File
@@ -430,7 +430,7 @@ model AssetComment {
/// [AnnotationList]
annotation Json?
second Float?
sessionId String? @unique @map("session_id")
sessionId String? @map("session_id")
session AgentSession? @relation(fields: [sessionId], references: [id], onDelete: SetNull)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@ -658,7 +658,7 @@ model AgentSession {
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
entries AgentSessionEntry[]
comment AssetComment?
comments AssetComment[]
@@map("agent_sessions")
}
File diff suppressed because one or more lines are too long
+58 -44
View File
@@ -203,7 +203,7 @@ export type AgentSessionWhereInput = {
agent?: Prisma.XOR<Prisma.AgentScalarRelationFilter, Prisma.AgentWhereInput>
user?: Prisma.XOR<Prisma.UserNullableScalarRelationFilter, Prisma.UserWhereInput> | null
entries?: Prisma.AgentSessionEntryListRelationFilter
comment?: Prisma.XOR<Prisma.AssetCommentNullableScalarRelationFilter, Prisma.AssetCommentWhereInput> | null
comments?: Prisma.AssetCommentListRelationFilter
}
export type AgentSessionOrderByWithRelationInput = {
@@ -217,7 +217,7 @@ export type AgentSessionOrderByWithRelationInput = {
agent?: Prisma.AgentOrderByWithRelationInput
user?: Prisma.UserOrderByWithRelationInput
entries?: Prisma.AgentSessionEntryOrderByRelationAggregateInput
comment?: Prisma.AssetCommentOrderByWithRelationInput
comments?: Prisma.AssetCommentOrderByRelationAggregateInput
}
export type AgentSessionWhereUniqueInput = Prisma.AtLeast<{
@@ -234,7 +234,7 @@ export type AgentSessionWhereUniqueInput = Prisma.AtLeast<{
agent?: Prisma.XOR<Prisma.AgentScalarRelationFilter, Prisma.AgentWhereInput>
user?: Prisma.XOR<Prisma.UserNullableScalarRelationFilter, Prisma.UserWhereInput> | null
entries?: Prisma.AgentSessionEntryListRelationFilter
comment?: Prisma.XOR<Prisma.AssetCommentNullableScalarRelationFilter, Prisma.AssetCommentWhereInput> | null
comments?: Prisma.AssetCommentListRelationFilter
}, "id">
export type AgentSessionOrderByWithAggregationInput = {
@@ -272,7 +272,7 @@ export type AgentSessionCreateInput = {
agent: Prisma.AgentCreateNestedOneWithoutAgentSessionsInput
user?: Prisma.UserCreateNestedOneWithoutAgentSessionsInput
entries?: Prisma.AgentSessionEntryCreateNestedManyWithoutSessionInput
comment?: Prisma.AssetCommentCreateNestedOneWithoutSessionInput
comments?: Prisma.AssetCommentCreateNestedManyWithoutSessionInput
}
export type AgentSessionUncheckedCreateInput = {
@@ -284,7 +284,7 @@ export type AgentSessionUncheckedCreateInput = {
createdAt?: Date | string
updatedAt?: Date | string
entries?: Prisma.AgentSessionEntryUncheckedCreateNestedManyWithoutSessionInput
comment?: Prisma.AssetCommentUncheckedCreateNestedOneWithoutSessionInput
comments?: Prisma.AssetCommentUncheckedCreateNestedManyWithoutSessionInput
}
export type AgentSessionUpdateInput = {
@@ -296,7 +296,7 @@ export type AgentSessionUpdateInput = {
agent?: Prisma.AgentUpdateOneRequiredWithoutAgentSessionsNestedInput
user?: Prisma.UserUpdateOneWithoutAgentSessionsNestedInput
entries?: Prisma.AgentSessionEntryUpdateManyWithoutSessionNestedInput
comment?: Prisma.AssetCommentUpdateOneWithoutSessionNestedInput
comments?: Prisma.AssetCommentUpdateManyWithoutSessionNestedInput
}
export type AgentSessionUncheckedUpdateInput = {
@@ -308,7 +308,7 @@ export type AgentSessionUncheckedUpdateInput = {
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
entries?: Prisma.AgentSessionEntryUncheckedUpdateManyWithoutSessionNestedInput
comment?: Prisma.AssetCommentUncheckedUpdateOneWithoutSessionNestedInput
comments?: Prisma.AssetCommentUncheckedUpdateManyWithoutSessionNestedInput
}
export type AgentSessionCreateManyInput = {
@@ -431,20 +431,20 @@ export type AgentSessionUncheckedUpdateManyWithoutUserNestedInput = {
deleteMany?: Prisma.AgentSessionScalarWhereInput | Prisma.AgentSessionScalarWhereInput[]
}
export type AgentSessionCreateNestedOneWithoutCommentInput = {
create?: Prisma.XOR<Prisma.AgentSessionCreateWithoutCommentInput, Prisma.AgentSessionUncheckedCreateWithoutCommentInput>
connectOrCreate?: Prisma.AgentSessionCreateOrConnectWithoutCommentInput
export type AgentSessionCreateNestedOneWithoutCommentsInput = {
create?: Prisma.XOR<Prisma.AgentSessionCreateWithoutCommentsInput, Prisma.AgentSessionUncheckedCreateWithoutCommentsInput>
connectOrCreate?: Prisma.AgentSessionCreateOrConnectWithoutCommentsInput
connect?: Prisma.AgentSessionWhereUniqueInput
}
export type AgentSessionUpdateOneWithoutCommentNestedInput = {
create?: Prisma.XOR<Prisma.AgentSessionCreateWithoutCommentInput, Prisma.AgentSessionUncheckedCreateWithoutCommentInput>
connectOrCreate?: Prisma.AgentSessionCreateOrConnectWithoutCommentInput
upsert?: Prisma.AgentSessionUpsertWithoutCommentInput
export type AgentSessionUpdateOneWithoutCommentsNestedInput = {
create?: Prisma.XOR<Prisma.AgentSessionCreateWithoutCommentsInput, Prisma.AgentSessionUncheckedCreateWithoutCommentsInput>
connectOrCreate?: Prisma.AgentSessionCreateOrConnectWithoutCommentsInput
upsert?: Prisma.AgentSessionUpsertWithoutCommentsInput
disconnect?: Prisma.AgentSessionWhereInput | boolean
delete?: Prisma.AgentSessionWhereInput | boolean
connect?: Prisma.AgentSessionWhereUniqueInput
update?: Prisma.XOR<Prisma.XOR<Prisma.AgentSessionUpdateToOneWithWhereWithoutCommentInput, Prisma.AgentSessionUpdateWithoutCommentInput>, Prisma.AgentSessionUncheckedUpdateWithoutCommentInput>
update?: Prisma.XOR<Prisma.XOR<Prisma.AgentSessionUpdateToOneWithWhereWithoutCommentsInput, Prisma.AgentSessionUpdateWithoutCommentsInput>, Prisma.AgentSessionUncheckedUpdateWithoutCommentsInput>
}
export type AgentSessionCreateNestedManyWithoutAgentInput = {
@@ -511,7 +511,7 @@ export type AgentSessionCreateWithoutUserInput = {
updatedAt?: Date | string
agent: Prisma.AgentCreateNestedOneWithoutAgentSessionsInput
entries?: Prisma.AgentSessionEntryCreateNestedManyWithoutSessionInput
comment?: Prisma.AssetCommentCreateNestedOneWithoutSessionInput
comments?: Prisma.AssetCommentCreateNestedManyWithoutSessionInput
}
export type AgentSessionUncheckedCreateWithoutUserInput = {
@@ -522,7 +522,7 @@ export type AgentSessionUncheckedCreateWithoutUserInput = {
createdAt?: Date | string
updatedAt?: Date | string
entries?: Prisma.AgentSessionEntryUncheckedCreateNestedManyWithoutSessionInput
comment?: Prisma.AssetCommentUncheckedCreateNestedOneWithoutSessionInput
comments?: Prisma.AssetCommentUncheckedCreateNestedManyWithoutSessionInput
}
export type AgentSessionCreateOrConnectWithoutUserInput = {
@@ -564,7 +564,7 @@ export type AgentSessionScalarWhereInput = {
updatedAt?: Prisma.DateTimeFilter<"AgentSession"> | Date | string
}
export type AgentSessionCreateWithoutCommentInput = {
export type AgentSessionCreateWithoutCommentsInput = {
id?: string
cwd: string
leafId?: string | null
@@ -575,7 +575,7 @@ export type AgentSessionCreateWithoutCommentInput = {
entries?: Prisma.AgentSessionEntryCreateNestedManyWithoutSessionInput
}
export type AgentSessionUncheckedCreateWithoutCommentInput = {
export type AgentSessionUncheckedCreateWithoutCommentsInput = {
id?: string
agentId: string
userId?: string | null
@@ -586,23 +586,23 @@ export type AgentSessionUncheckedCreateWithoutCommentInput = {
entries?: Prisma.AgentSessionEntryUncheckedCreateNestedManyWithoutSessionInput
}
export type AgentSessionCreateOrConnectWithoutCommentInput = {
export type AgentSessionCreateOrConnectWithoutCommentsInput = {
where: Prisma.AgentSessionWhereUniqueInput
create: Prisma.XOR<Prisma.AgentSessionCreateWithoutCommentInput, Prisma.AgentSessionUncheckedCreateWithoutCommentInput>
create: Prisma.XOR<Prisma.AgentSessionCreateWithoutCommentsInput, Prisma.AgentSessionUncheckedCreateWithoutCommentsInput>
}
export type AgentSessionUpsertWithoutCommentInput = {
update: Prisma.XOR<Prisma.AgentSessionUpdateWithoutCommentInput, Prisma.AgentSessionUncheckedUpdateWithoutCommentInput>
create: Prisma.XOR<Prisma.AgentSessionCreateWithoutCommentInput, Prisma.AgentSessionUncheckedCreateWithoutCommentInput>
export type AgentSessionUpsertWithoutCommentsInput = {
update: Prisma.XOR<Prisma.AgentSessionUpdateWithoutCommentsInput, Prisma.AgentSessionUncheckedUpdateWithoutCommentsInput>
create: Prisma.XOR<Prisma.AgentSessionCreateWithoutCommentsInput, Prisma.AgentSessionUncheckedCreateWithoutCommentsInput>
where?: Prisma.AgentSessionWhereInput
}
export type AgentSessionUpdateToOneWithWhereWithoutCommentInput = {
export type AgentSessionUpdateToOneWithWhereWithoutCommentsInput = {
where?: Prisma.AgentSessionWhereInput
data: Prisma.XOR<Prisma.AgentSessionUpdateWithoutCommentInput, Prisma.AgentSessionUncheckedUpdateWithoutCommentInput>
data: Prisma.XOR<Prisma.AgentSessionUpdateWithoutCommentsInput, Prisma.AgentSessionUncheckedUpdateWithoutCommentsInput>
}
export type AgentSessionUpdateWithoutCommentInput = {
export type AgentSessionUpdateWithoutCommentsInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
cwd?: Prisma.StringFieldUpdateOperationsInput | string
leafId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
@@ -613,7 +613,7 @@ export type AgentSessionUpdateWithoutCommentInput = {
entries?: Prisma.AgentSessionEntryUpdateManyWithoutSessionNestedInput
}
export type AgentSessionUncheckedUpdateWithoutCommentInput = {
export type AgentSessionUncheckedUpdateWithoutCommentsInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
agentId?: Prisma.StringFieldUpdateOperationsInput | string
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
@@ -632,7 +632,7 @@ export type AgentSessionCreateWithoutAgentInput = {
updatedAt?: Date | string
user?: Prisma.UserCreateNestedOneWithoutAgentSessionsInput
entries?: Prisma.AgentSessionEntryCreateNestedManyWithoutSessionInput
comment?: Prisma.AssetCommentCreateNestedOneWithoutSessionInput
comments?: Prisma.AssetCommentCreateNestedManyWithoutSessionInput
}
export type AgentSessionUncheckedCreateWithoutAgentInput = {
@@ -643,7 +643,7 @@ export type AgentSessionUncheckedCreateWithoutAgentInput = {
createdAt?: Date | string
updatedAt?: Date | string
entries?: Prisma.AgentSessionEntryUncheckedCreateNestedManyWithoutSessionInput
comment?: Prisma.AssetCommentUncheckedCreateNestedOneWithoutSessionInput
comments?: Prisma.AssetCommentUncheckedCreateNestedManyWithoutSessionInput
}
export type AgentSessionCreateOrConnectWithoutAgentInput = {
@@ -680,7 +680,7 @@ export type AgentSessionCreateWithoutEntriesInput = {
updatedAt?: Date | string
agent: Prisma.AgentCreateNestedOneWithoutAgentSessionsInput
user?: Prisma.UserCreateNestedOneWithoutAgentSessionsInput
comment?: Prisma.AssetCommentCreateNestedOneWithoutSessionInput
comments?: Prisma.AssetCommentCreateNestedManyWithoutSessionInput
}
export type AgentSessionUncheckedCreateWithoutEntriesInput = {
@@ -691,7 +691,7 @@ export type AgentSessionUncheckedCreateWithoutEntriesInput = {
leafId?: string | null
createdAt?: Date | string
updatedAt?: Date | string
comment?: Prisma.AssetCommentUncheckedCreateNestedOneWithoutSessionInput
comments?: Prisma.AssetCommentUncheckedCreateNestedManyWithoutSessionInput
}
export type AgentSessionCreateOrConnectWithoutEntriesInput = {
@@ -718,7 +718,7 @@ export type AgentSessionUpdateWithoutEntriesInput = {
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
agent?: Prisma.AgentUpdateOneRequiredWithoutAgentSessionsNestedInput
user?: Prisma.UserUpdateOneWithoutAgentSessionsNestedInput
comment?: Prisma.AssetCommentUpdateOneWithoutSessionNestedInput
comments?: Prisma.AssetCommentUpdateManyWithoutSessionNestedInput
}
export type AgentSessionUncheckedUpdateWithoutEntriesInput = {
@@ -729,7 +729,7 @@ export type AgentSessionUncheckedUpdateWithoutEntriesInput = {
leafId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
comment?: Prisma.AssetCommentUncheckedUpdateOneWithoutSessionNestedInput
comments?: Prisma.AssetCommentUncheckedUpdateManyWithoutSessionNestedInput
}
export type AgentSessionCreateManyUserInput = {
@@ -749,7 +749,7 @@ export type AgentSessionUpdateWithoutUserInput = {
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
agent?: Prisma.AgentUpdateOneRequiredWithoutAgentSessionsNestedInput
entries?: Prisma.AgentSessionEntryUpdateManyWithoutSessionNestedInput
comment?: Prisma.AssetCommentUpdateOneWithoutSessionNestedInput
comments?: Prisma.AssetCommentUpdateManyWithoutSessionNestedInput
}
export type AgentSessionUncheckedUpdateWithoutUserInput = {
@@ -760,7 +760,7 @@ export type AgentSessionUncheckedUpdateWithoutUserInput = {
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
entries?: Prisma.AgentSessionEntryUncheckedUpdateManyWithoutSessionNestedInput
comment?: Prisma.AssetCommentUncheckedUpdateOneWithoutSessionNestedInput
comments?: Prisma.AssetCommentUncheckedUpdateManyWithoutSessionNestedInput
}
export type AgentSessionUncheckedUpdateManyWithoutUserInput = {
@@ -789,7 +789,7 @@ export type AgentSessionUpdateWithoutAgentInput = {
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
user?: Prisma.UserUpdateOneWithoutAgentSessionsNestedInput
entries?: Prisma.AgentSessionEntryUpdateManyWithoutSessionNestedInput
comment?: Prisma.AssetCommentUpdateOneWithoutSessionNestedInput
comments?: Prisma.AssetCommentUpdateManyWithoutSessionNestedInput
}
export type AgentSessionUncheckedUpdateWithoutAgentInput = {
@@ -800,7 +800,7 @@ export type AgentSessionUncheckedUpdateWithoutAgentInput = {
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
entries?: Prisma.AgentSessionEntryUncheckedUpdateManyWithoutSessionNestedInput
comment?: Prisma.AssetCommentUncheckedUpdateOneWithoutSessionNestedInput
comments?: Prisma.AssetCommentUncheckedUpdateManyWithoutSessionNestedInput
}
export type AgentSessionUncheckedUpdateManyWithoutAgentInput = {
@@ -819,10 +819,12 @@ export type AgentSessionUncheckedUpdateManyWithoutAgentInput = {
export type AgentSessionCountOutputType = {
entries: number
comments: number
}
export type AgentSessionCountOutputTypeSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
entries?: boolean | AgentSessionCountOutputTypeCountEntriesArgs
comments?: boolean | AgentSessionCountOutputTypeCountCommentsArgs
}
/**
@@ -842,6 +844,13 @@ export type AgentSessionCountOutputTypeCountEntriesArgs<ExtArgs extends runtime.
where?: Prisma.AgentSessionEntryWhereInput
}
/**
* AgentSessionCountOutputType without action
*/
export type AgentSessionCountOutputTypeCountCommentsArgs<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
where?: Prisma.AssetCommentWhereInput
}
export type AgentSessionSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetSelect<{
id?: boolean
@@ -854,7 +863,7 @@ export type AgentSessionSelect<ExtArgs extends runtime.Types.Extensions.Internal
agent?: boolean | Prisma.AgentDefaultArgs<ExtArgs>
user?: boolean | Prisma.AgentSession$userArgs<ExtArgs>
entries?: boolean | Prisma.AgentSession$entriesArgs<ExtArgs>
comment?: boolean | Prisma.AgentSession$commentArgs<ExtArgs>
comments?: boolean | Prisma.AgentSession$commentsArgs<ExtArgs>
_count?: boolean | Prisma.AgentSessionCountOutputTypeDefaultArgs<ExtArgs>
}, ExtArgs["result"]["agentSession"]>
@@ -897,7 +906,7 @@ export type AgentSessionInclude<ExtArgs extends runtime.Types.Extensions.Interna
agent?: boolean | Prisma.AgentDefaultArgs<ExtArgs>
user?: boolean | Prisma.AgentSession$userArgs<ExtArgs>
entries?: boolean | Prisma.AgentSession$entriesArgs<ExtArgs>
comment?: boolean | Prisma.AgentSession$commentArgs<ExtArgs>
comments?: boolean | Prisma.AgentSession$commentsArgs<ExtArgs>
_count?: boolean | Prisma.AgentSessionCountOutputTypeDefaultArgs<ExtArgs>
}
export type AgentSessionIncludeCreateManyAndReturn<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
@@ -915,7 +924,7 @@ export type $AgentSessionPayload<ExtArgs extends runtime.Types.Extensions.Intern
agent: Prisma.$AgentPayload<ExtArgs>
user: Prisma.$UserPayload<ExtArgs> | null
entries: Prisma.$AgentSessionEntryPayload<ExtArgs>[]
comment: Prisma.$AssetCommentPayload<ExtArgs> | null
comments: Prisma.$AssetCommentPayload<ExtArgs>[]
}
scalars: runtime.Types.Extensions.GetPayloadResult<{
id: string
@@ -1322,7 +1331,7 @@ export interface Prisma__AgentSessionClient<T, Null = never, ExtArgs extends run
agent<T extends Prisma.AgentDefaultArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.AgentDefaultArgs<ExtArgs>>): Prisma.Prisma__AgentClient<runtime.Types.Result.GetResult<Prisma.$AgentPayload<ExtArgs>, T, "findUniqueOrThrow", GlobalOmitOptions> | Null, Null, ExtArgs, GlobalOmitOptions>
user<T extends Prisma.AgentSession$userArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.AgentSession$userArgs<ExtArgs>>): Prisma.Prisma__UserClient<runtime.Types.Result.GetResult<Prisma.$UserPayload<ExtArgs>, T, "findUniqueOrThrow", GlobalOmitOptions> | null, null, ExtArgs, GlobalOmitOptions>
entries<T extends Prisma.AgentSession$entriesArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.AgentSession$entriesArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$AgentSessionEntryPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
comment<T extends Prisma.AgentSession$commentArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.AgentSession$commentArgs<ExtArgs>>): Prisma.Prisma__AssetCommentClient<runtime.Types.Result.GetResult<Prisma.$AssetCommentPayload<ExtArgs>, T, "findUniqueOrThrow", GlobalOmitOptions> | null, null, ExtArgs, GlobalOmitOptions>
comments<T extends Prisma.AgentSession$commentsArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.AgentSession$commentsArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$AssetCommentPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
@@ -1803,9 +1812,9 @@ export type AgentSession$entriesArgs<ExtArgs extends runtime.Types.Extensions.In
}
/**
* AgentSession.comment
* AgentSession.comments
*/
export type AgentSession$commentArgs<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
export type AgentSession$commentsArgs<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
/**
* Select specific fields to fetch from the AssetComment
*/
@@ -1819,6 +1828,11 @@ export type AgentSession$commentArgs<ExtArgs extends runtime.Types.Extensions.In
*/
include?: Prisma.AssetCommentInclude<ExtArgs> | null
where?: Prisma.AssetCommentWhereInput
orderBy?: Prisma.AssetCommentOrderByWithRelationInput | Prisma.AssetCommentOrderByWithRelationInput[]
cursor?: Prisma.AssetCommentWhereUniqueInput
take?: number
skip?: number
distinct?: Prisma.AssetCommentScalarFieldEnum | Prisma.AssetCommentScalarFieldEnum[]
}
/**
+114 -70
View File
@@ -283,13 +283,13 @@ export type AssetCommentOrderByWithRelationInput = {
export type AssetCommentWhereUniqueInput = Prisma.AtLeast<{
id?: string
sessionId?: string
AND?: Prisma.AssetCommentWhereInput | Prisma.AssetCommentWhereInput[]
OR?: Prisma.AssetCommentWhereInput[]
NOT?: Prisma.AssetCommentWhereInput | Prisma.AssetCommentWhereInput[]
message?: Prisma.StringNullableFilter<"AssetComment"> | string | null
annotation?: Prisma.JsonNullableFilter<"AssetComment">
second?: Prisma.FloatNullableFilter<"AssetComment"> | number | null
sessionId?: Prisma.StringNullableFilter<"AssetComment"> | string | null
createdAt?: Prisma.DateTimeFilter<"AssetComment"> | Date | string
updatedAt?: Prisma.DateTimeFilter<"AssetComment"> | Date | string
assetId?: Prisma.StringFilter<"AssetComment"> | string
@@ -301,7 +301,7 @@ export type AssetCommentWhereUniqueInput = Prisma.AtLeast<{
replyTo?: Prisma.XOR<Prisma.AssetCommentNullableScalarRelationFilter, Prisma.AssetCommentWhereInput> | null
replies?: Prisma.AssetCommentListRelationFilter
attachments?: Prisma.AssetCommentAttachmentListRelationFilter
}, "id" | "sessionId">
}, "id">
export type AssetCommentOrderByWithAggregationInput = {
id?: Prisma.SortOrder
@@ -344,7 +344,7 @@ export type AssetCommentCreateInput = {
second?: number | null
createdAt?: Date | string
updatedAt?: Date | string
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentInput
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentsInput
asset: Prisma.AssetCreateNestedOneWithoutCommentsInput
creator?: Prisma.UserCreateNestedOneWithoutCommentsInput
replyTo?: Prisma.AssetCommentCreateNestedOneWithoutRepliesInput
@@ -374,7 +374,7 @@ export type AssetCommentUpdateInput = {
second?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
session?: Prisma.AgentSessionUpdateOneWithoutCommentNestedInput
session?: Prisma.AgentSessionUpdateOneWithoutCommentsNestedInput
asset?: Prisma.AssetUpdateOneRequiredWithoutCommentsNestedInput
creator?: Prisma.UserUpdateOneWithoutCommentsNestedInput
replyTo?: Prisma.AssetCommentUpdateOneWithoutRepliesNestedInput
@@ -653,36 +653,46 @@ export type AssetCommentUpdateOneRequiredWithoutAttachmentsNestedInput = {
update?: Prisma.XOR<Prisma.XOR<Prisma.AssetCommentUpdateToOneWithWhereWithoutAttachmentsInput, Prisma.AssetCommentUpdateWithoutAttachmentsInput>, Prisma.AssetCommentUncheckedUpdateWithoutAttachmentsInput>
}
export type AssetCommentCreateNestedOneWithoutSessionInput = {
create?: Prisma.XOR<Prisma.AssetCommentCreateWithoutSessionInput, Prisma.AssetCommentUncheckedCreateWithoutSessionInput>
connectOrCreate?: Prisma.AssetCommentCreateOrConnectWithoutSessionInput
connect?: Prisma.AssetCommentWhereUniqueInput
export type AssetCommentCreateNestedManyWithoutSessionInput = {
create?: Prisma.XOR<Prisma.AssetCommentCreateWithoutSessionInput, Prisma.AssetCommentUncheckedCreateWithoutSessionInput> | Prisma.AssetCommentCreateWithoutSessionInput[] | Prisma.AssetCommentUncheckedCreateWithoutSessionInput[]
connectOrCreate?: Prisma.AssetCommentCreateOrConnectWithoutSessionInput | Prisma.AssetCommentCreateOrConnectWithoutSessionInput[]
createMany?: Prisma.AssetCommentCreateManySessionInputEnvelope
connect?: Prisma.AssetCommentWhereUniqueInput | Prisma.AssetCommentWhereUniqueInput[]
}
export type AssetCommentUncheckedCreateNestedOneWithoutSessionInput = {
create?: Prisma.XOR<Prisma.AssetCommentCreateWithoutSessionInput, Prisma.AssetCommentUncheckedCreateWithoutSessionInput>
connectOrCreate?: Prisma.AssetCommentCreateOrConnectWithoutSessionInput
connect?: Prisma.AssetCommentWhereUniqueInput
export type AssetCommentUncheckedCreateNestedManyWithoutSessionInput = {
create?: Prisma.XOR<Prisma.AssetCommentCreateWithoutSessionInput, Prisma.AssetCommentUncheckedCreateWithoutSessionInput> | Prisma.AssetCommentCreateWithoutSessionInput[] | Prisma.AssetCommentUncheckedCreateWithoutSessionInput[]
connectOrCreate?: Prisma.AssetCommentCreateOrConnectWithoutSessionInput | Prisma.AssetCommentCreateOrConnectWithoutSessionInput[]
createMany?: Prisma.AssetCommentCreateManySessionInputEnvelope
connect?: Prisma.AssetCommentWhereUniqueInput | Prisma.AssetCommentWhereUniqueInput[]
}
export type AssetCommentUpdateOneWithoutSessionNestedInput = {
create?: Prisma.XOR<Prisma.AssetCommentCreateWithoutSessionInput, Prisma.AssetCommentUncheckedCreateWithoutSessionInput>
connectOrCreate?: Prisma.AssetCommentCreateOrConnectWithoutSessionInput
upsert?: Prisma.AssetCommentUpsertWithoutSessionInput
disconnect?: Prisma.AssetCommentWhereInput | boolean
delete?: Prisma.AssetCommentWhereInput | boolean
connect?: Prisma.AssetCommentWhereUniqueInput
update?: Prisma.XOR<Prisma.XOR<Prisma.AssetCommentUpdateToOneWithWhereWithoutSessionInput, Prisma.AssetCommentUpdateWithoutSessionInput>, Prisma.AssetCommentUncheckedUpdateWithoutSessionInput>
export type AssetCommentUpdateManyWithoutSessionNestedInput = {
create?: Prisma.XOR<Prisma.AssetCommentCreateWithoutSessionInput, Prisma.AssetCommentUncheckedCreateWithoutSessionInput> | Prisma.AssetCommentCreateWithoutSessionInput[] | Prisma.AssetCommentUncheckedCreateWithoutSessionInput[]
connectOrCreate?: Prisma.AssetCommentCreateOrConnectWithoutSessionInput | Prisma.AssetCommentCreateOrConnectWithoutSessionInput[]
upsert?: Prisma.AssetCommentUpsertWithWhereUniqueWithoutSessionInput | Prisma.AssetCommentUpsertWithWhereUniqueWithoutSessionInput[]
createMany?: Prisma.AssetCommentCreateManySessionInputEnvelope
set?: Prisma.AssetCommentWhereUniqueInput | Prisma.AssetCommentWhereUniqueInput[]
disconnect?: Prisma.AssetCommentWhereUniqueInput | Prisma.AssetCommentWhereUniqueInput[]
delete?: Prisma.AssetCommentWhereUniqueInput | Prisma.AssetCommentWhereUniqueInput[]
connect?: Prisma.AssetCommentWhereUniqueInput | Prisma.AssetCommentWhereUniqueInput[]
update?: Prisma.AssetCommentUpdateWithWhereUniqueWithoutSessionInput | Prisma.AssetCommentUpdateWithWhereUniqueWithoutSessionInput[]
updateMany?: Prisma.AssetCommentUpdateManyWithWhereWithoutSessionInput | Prisma.AssetCommentUpdateManyWithWhereWithoutSessionInput[]
deleteMany?: Prisma.AssetCommentScalarWhereInput | Prisma.AssetCommentScalarWhereInput[]
}
export type AssetCommentUncheckedUpdateOneWithoutSessionNestedInput = {
create?: Prisma.XOR<Prisma.AssetCommentCreateWithoutSessionInput, Prisma.AssetCommentUncheckedCreateWithoutSessionInput>
connectOrCreate?: Prisma.AssetCommentCreateOrConnectWithoutSessionInput
upsert?: Prisma.AssetCommentUpsertWithoutSessionInput
disconnect?: Prisma.AssetCommentWhereInput | boolean
delete?: Prisma.AssetCommentWhereInput | boolean
connect?: Prisma.AssetCommentWhereUniqueInput
update?: Prisma.XOR<Prisma.XOR<Prisma.AssetCommentUpdateToOneWithWhereWithoutSessionInput, Prisma.AssetCommentUpdateWithoutSessionInput>, Prisma.AssetCommentUncheckedUpdateWithoutSessionInput>
export type AssetCommentUncheckedUpdateManyWithoutSessionNestedInput = {
create?: Prisma.XOR<Prisma.AssetCommentCreateWithoutSessionInput, Prisma.AssetCommentUncheckedCreateWithoutSessionInput> | Prisma.AssetCommentCreateWithoutSessionInput[] | Prisma.AssetCommentUncheckedCreateWithoutSessionInput[]
connectOrCreate?: Prisma.AssetCommentCreateOrConnectWithoutSessionInput | Prisma.AssetCommentCreateOrConnectWithoutSessionInput[]
upsert?: Prisma.AssetCommentUpsertWithWhereUniqueWithoutSessionInput | Prisma.AssetCommentUpsertWithWhereUniqueWithoutSessionInput[]
createMany?: Prisma.AssetCommentCreateManySessionInputEnvelope
set?: Prisma.AssetCommentWhereUniqueInput | Prisma.AssetCommentWhereUniqueInput[]
disconnect?: Prisma.AssetCommentWhereUniqueInput | Prisma.AssetCommentWhereUniqueInput[]
delete?: Prisma.AssetCommentWhereUniqueInput | Prisma.AssetCommentWhereUniqueInput[]
connect?: Prisma.AssetCommentWhereUniqueInput | Prisma.AssetCommentWhereUniqueInput[]
update?: Prisma.AssetCommentUpdateWithWhereUniqueWithoutSessionInput | Prisma.AssetCommentUpdateWithWhereUniqueWithoutSessionInput[]
updateMany?: Prisma.AssetCommentUpdateManyWithWhereWithoutSessionInput | Prisma.AssetCommentUpdateManyWithWhereWithoutSessionInput[]
deleteMany?: Prisma.AssetCommentScalarWhereInput | Prisma.AssetCommentScalarWhereInput[]
}
export type AssetCommentCreateWithoutCreatorInput = {
@@ -692,7 +702,7 @@ export type AssetCommentCreateWithoutCreatorInput = {
second?: number | null
createdAt?: Date | string
updatedAt?: Date | string
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentInput
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentsInput
asset: Prisma.AssetCreateNestedOneWithoutCommentsInput
replyTo?: Prisma.AssetCommentCreateNestedOneWithoutRepliesInput
replies?: Prisma.AssetCommentCreateNestedManyWithoutReplyToInput
@@ -762,7 +772,7 @@ export type AssetCommentCreateWithoutAssetInput = {
second?: number | null
createdAt?: Date | string
updatedAt?: Date | string
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentInput
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentsInput
creator?: Prisma.UserCreateNestedOneWithoutCommentsInput
replyTo?: Prisma.AssetCommentCreateNestedOneWithoutRepliesInput
replies?: Prisma.AssetCommentCreateNestedManyWithoutReplyToInput
@@ -816,7 +826,7 @@ export type AssetCommentCreateWithoutRepliesInput = {
second?: number | null
createdAt?: Date | string
updatedAt?: Date | string
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentInput
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentsInput
asset: Prisma.AssetCreateNestedOneWithoutCommentsInput
creator?: Prisma.UserCreateNestedOneWithoutCommentsInput
replyTo?: Prisma.AssetCommentCreateNestedOneWithoutRepliesInput
@@ -849,7 +859,7 @@ export type AssetCommentCreateWithoutReplyToInput = {
second?: number | null
createdAt?: Date | string
updatedAt?: Date | string
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentInput
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentsInput
asset: Prisma.AssetCreateNestedOneWithoutCommentsInput
creator?: Prisma.UserCreateNestedOneWithoutCommentsInput
replies?: Prisma.AssetCommentCreateNestedManyWithoutReplyToInput
@@ -898,7 +908,7 @@ export type AssetCommentUpdateWithoutRepliesInput = {
second?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
session?: Prisma.AgentSessionUpdateOneWithoutCommentNestedInput
session?: Prisma.AgentSessionUpdateOneWithoutCommentsNestedInput
asset?: Prisma.AssetUpdateOneRequiredWithoutCommentsNestedInput
creator?: Prisma.UserUpdateOneWithoutCommentsNestedInput
replyTo?: Prisma.AssetCommentUpdateOneWithoutRepliesNestedInput
@@ -942,7 +952,7 @@ export type AssetCommentCreateWithoutAttachmentsInput = {
second?: number | null
createdAt?: Date | string
updatedAt?: Date | string
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentInput
session?: Prisma.AgentSessionCreateNestedOneWithoutCommentsInput
asset: Prisma.AssetCreateNestedOneWithoutCommentsInput
creator?: Prisma.UserCreateNestedOneWithoutCommentsInput
replyTo?: Prisma.AssetCommentCreateNestedOneWithoutRepliesInput
@@ -986,7 +996,7 @@ export type AssetCommentUpdateWithoutAttachmentsInput = {
second?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
session?: Prisma.AgentSessionUpdateOneWithoutCommentNestedInput
session?: Prisma.AgentSessionUpdateOneWithoutCommentsNestedInput
asset?: Prisma.AssetUpdateOneRequiredWithoutCommentsNestedInput
creator?: Prisma.UserUpdateOneWithoutCommentsNestedInput
replyTo?: Prisma.AssetCommentUpdateOneWithoutRepliesNestedInput
@@ -1040,43 +1050,25 @@ export type AssetCommentCreateOrConnectWithoutSessionInput = {
create: Prisma.XOR<Prisma.AssetCommentCreateWithoutSessionInput, Prisma.AssetCommentUncheckedCreateWithoutSessionInput>
}
export type AssetCommentUpsertWithoutSessionInput = {
update: Prisma.XOR<Prisma.AssetCommentUpdateWithoutSessionInput, Prisma.AssetCommentUncheckedUpdateWithoutSessionInput>
create: Prisma.XOR<Prisma.AssetCommentCreateWithoutSessionInput, Prisma.AssetCommentUncheckedCreateWithoutSessionInput>
where?: Prisma.AssetCommentWhereInput
export type AssetCommentCreateManySessionInputEnvelope = {
data: Prisma.AssetCommentCreateManySessionInput | Prisma.AssetCommentCreateManySessionInput[]
skipDuplicates?: boolean
}
export type AssetCommentUpdateToOneWithWhereWithoutSessionInput = {
where?: Prisma.AssetCommentWhereInput
export type AssetCommentUpsertWithWhereUniqueWithoutSessionInput = {
where: Prisma.AssetCommentWhereUniqueInput
update: Prisma.XOR<Prisma.AssetCommentUpdateWithoutSessionInput, Prisma.AssetCommentUncheckedUpdateWithoutSessionInput>
create: Prisma.XOR<Prisma.AssetCommentCreateWithoutSessionInput, Prisma.AssetCommentUncheckedCreateWithoutSessionInput>
}
export type AssetCommentUpdateWithWhereUniqueWithoutSessionInput = {
where: Prisma.AssetCommentWhereUniqueInput
data: Prisma.XOR<Prisma.AssetCommentUpdateWithoutSessionInput, Prisma.AssetCommentUncheckedUpdateWithoutSessionInput>
}
export type AssetCommentUpdateWithoutSessionInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
message?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
annotation?:PrismaJson.AnnotationList | Prisma.NullableJsonNullValueInput
second?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
asset?: Prisma.AssetUpdateOneRequiredWithoutCommentsNestedInput
creator?: Prisma.UserUpdateOneWithoutCommentsNestedInput
replyTo?: Prisma.AssetCommentUpdateOneWithoutRepliesNestedInput
replies?: Prisma.AssetCommentUpdateManyWithoutReplyToNestedInput
attachments?: Prisma.AssetCommentAttachmentUpdateManyWithoutCommentNestedInput
}
export type AssetCommentUncheckedUpdateWithoutSessionInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
message?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
annotation?:PrismaJson.AnnotationList | Prisma.NullableJsonNullValueInput
second?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
assetId?: Prisma.StringFieldUpdateOperationsInput | string
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
replies?: Prisma.AssetCommentUncheckedUpdateManyWithoutReplyToNestedInput
attachments?: Prisma.AssetCommentAttachmentUncheckedUpdateManyWithoutCommentNestedInput
export type AssetCommentUpdateManyWithWhereWithoutSessionInput = {
where: Prisma.AssetCommentScalarWhereInput
data: Prisma.XOR<Prisma.AssetCommentUpdateManyMutationInput, Prisma.AssetCommentUncheckedUpdateManyWithoutSessionInput>
}
export type AssetCommentCreateManyCreatorInput = {
@@ -1098,7 +1090,7 @@ export type AssetCommentUpdateWithoutCreatorInput = {
second?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
session?: Prisma.AgentSessionUpdateOneWithoutCommentNestedInput
session?: Prisma.AgentSessionUpdateOneWithoutCommentsNestedInput
asset?: Prisma.AssetUpdateOneRequiredWithoutCommentsNestedInput
replyTo?: Prisma.AssetCommentUpdateOneWithoutRepliesNestedInput
replies?: Prisma.AssetCommentUpdateManyWithoutReplyToNestedInput
@@ -1150,7 +1142,7 @@ export type AssetCommentUpdateWithoutAssetInput = {
second?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
session?: Prisma.AgentSessionUpdateOneWithoutCommentNestedInput
session?: Prisma.AgentSessionUpdateOneWithoutCommentsNestedInput
creator?: Prisma.UserUpdateOneWithoutCommentsNestedInput
replyTo?: Prisma.AssetCommentUpdateOneWithoutRepliesNestedInput
replies?: Prisma.AssetCommentUpdateManyWithoutReplyToNestedInput
@@ -1202,7 +1194,7 @@ export type AssetCommentUpdateWithoutReplyToInput = {
second?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
session?: Prisma.AgentSessionUpdateOneWithoutCommentNestedInput
session?: Prisma.AgentSessionUpdateOneWithoutCommentsNestedInput
asset?: Prisma.AssetUpdateOneRequiredWithoutCommentsNestedInput
creator?: Prisma.UserUpdateOneWithoutCommentsNestedInput
replies?: Prisma.AssetCommentUpdateManyWithoutReplyToNestedInput
@@ -1235,6 +1227,58 @@ export type AssetCommentUncheckedUpdateManyWithoutReplyToInput = {
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
}
export type AssetCommentCreateManySessionInput = {
id?: string
message?: string | null
annotation?:PrismaJson.AnnotationList | Prisma.NullableJsonNullValueInput
second?: number | null
createdAt?: Date | string
updatedAt?: Date | string
assetId: string
creatorId?: string | null
replyToId?: string | null
}
export type AssetCommentUpdateWithoutSessionInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
message?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
annotation?:PrismaJson.AnnotationList | Prisma.NullableJsonNullValueInput
second?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
asset?: Prisma.AssetUpdateOneRequiredWithoutCommentsNestedInput
creator?: Prisma.UserUpdateOneWithoutCommentsNestedInput
replyTo?: Prisma.AssetCommentUpdateOneWithoutRepliesNestedInput
replies?: Prisma.AssetCommentUpdateManyWithoutReplyToNestedInput
attachments?: Prisma.AssetCommentAttachmentUpdateManyWithoutCommentNestedInput
}
export type AssetCommentUncheckedUpdateWithoutSessionInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
message?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
annotation?:PrismaJson.AnnotationList | Prisma.NullableJsonNullValueInput
second?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
assetId?: Prisma.StringFieldUpdateOperationsInput | string
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
replies?: Prisma.AssetCommentUncheckedUpdateManyWithoutReplyToNestedInput
attachments?: Prisma.AssetCommentAttachmentUncheckedUpdateManyWithoutCommentNestedInput
}
export type AssetCommentUncheckedUpdateManyWithoutSessionInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
message?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
annotation?:PrismaJson.AnnotationList | Prisma.NullableJsonNullValueInput
second?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
assetId?: Prisma.StringFieldUpdateOperationsInput | string
creatorId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
replyToId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
}
/**
* Count Type AssetCommentCountOutputType
+148
View File
@@ -658,6 +658,154 @@ describe('AssetService', () => {
expect(tasks.some((t) => (t.payload as any).agentId === 'default')).toBe(true)
})
it('implements agent comment interaction rules (Rule 1, 2, 3)', async () => {
const { user, project } = await setupBasicAssets()
const file = await prisma.asset.create({
data: {
name: 'rules-file',
type: AssetType.file,
projectId: project.id,
creatorId: user.id,
status: 'uploaded',
},
})
const botUser = await prisma.user.create({
data: {
name: 'Bot Agent',
type: 'agent',
email: 'rule-bot@shumai.ai',
},
})
const agent = await prisma.agent.create({
data: {
id: botUser.id,
teamId: project.teamId,
type: 'chat',
config: {
provider: 'google',
model: 'gemini-pro',
},
},
})
// Rule 1: user mentions agent in chat, and it's not in a reply
const c1 = await assetService.createComment({
assetId: file.id,
userId: user.id,
message: `Rule 1 test: Hello <@${agent.id}>`,
attachmentIds: [],
})
const tasksRule1 = await prisma.workflowTask.findMany({
where: { assetId: file.id, payload: { path: ['userCommentId'], equals: c1.id } },
})
expect(tasksRule1.length).toBe(1)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const p1 = tasksRule1[0].payload as any
expect(p1.agentId).toBe(agent.id)
expect(p1.sessionId).toBeUndefined()
expect(p1.explicitMention).toBe(true)
// Rule 2: user mentions agent in reply, and root is not an agent comment
const reply1 = await assetService.createComment({
assetId: file.id,
userId: user.id,
message: `Rule 2 reply: <@${agent.id}>`,
replyToId: c1.id,
attachmentIds: [],
})
const tasksRule2 = await prisma.workflowTask.findMany({
where: { assetId: file.id, payload: { path: ['userCommentId'], equals: reply1.id } },
})
expect(tasksRule2.length).toBe(1)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const p2 = tasksRule2[0].payload as any
expect(p2.agentId).toBe(agent.id)
expect(p2.sessionId).toBeUndefined()
expect(p2.explicitMention).toBe(true)
// Create a root user comment
const userRoot = await prisma.assetComment.create({
data: {
assetId: file.id,
creatorId: user.id,
message: 'User root comment',
},
})
// Create an agent session first for the foreign key constraint
await prisma.agentSession.create({
data: {
id: 'test-session-rule3',
agentId: botUser.id,
cwd: process.cwd(),
},
})
// Create an agent comment as a reply to userRoot with sessionId
const agentReply = await prisma.assetComment.create({
data: {
assetId: file.id,
creatorId: botUser.id,
message: 'Agent reply comment',
replyToId: userRoot.id,
sessionId: 'test-session-rule3',
},
})
// Rule 3a: any user creates a reply directly to the agent comment, no explicit mention
const reply3a = await assetService.createComment({
assetId: file.id,
userId: user.id,
message: 'Rule 3a: reply without mention',
replyToId: agentReply.id,
attachmentIds: [],
})
// Verify replyToId of reply3a was normalized to the root comment userRoot.id
const dbReply3a = await prisma.assetComment.findUnique({
where: { id: reply3a.id },
})
expect(dbReply3a?.replyToId).toBe(userRoot.id)
const tasksRule3a = await prisma.workflowTask.findMany({
where: { assetId: file.id, payload: { path: ['userCommentId'], equals: reply3a.id } },
})
expect(tasksRule3a.length).toBe(1)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const p3a = tasksRule3a[0].payload as any
expect(p3a.agentId).toBe(botUser.id)
expect(p3a.sessionId).toBe('test-session-rule3')
expect(p3a.explicitMention).toBe(false)
// Rule 3b: any user creates a reply directly to the agent comment, explicitly mentions agent
const reply3b = await assetService.createComment({
assetId: file.id,
userId: user.id,
message: `Rule 3b: reply with mention <@${botUser.id}>`,
replyToId: agentReply.id,
attachmentIds: [],
})
// Verify replyToId of reply3b was normalized to the root comment userRoot.id
const dbReply3b = await prisma.assetComment.findUnique({
where: { id: reply3b.id },
})
expect(dbReply3b?.replyToId).toBe(userRoot.id)
const tasksRule3b = await prisma.workflowTask.findMany({
where: { assetId: file.id, payload: { path: ['userCommentId'], equals: reply3b.id } },
})
expect(tasksRule3b.length).toBe(1)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const p3b = tasksRule3b[0].payload as any
expect(p3b.agentId).toBe(botUser.id)
expect(p3b.sessionId).toBe('test-session-rule3')
expect(p3b.explicitMention).toBe(true)
})
it('updates asset order correctly', async () => {
const { user, project } = await setupBasicAssets()
+51 -6
View File
@@ -771,6 +771,18 @@ export class AssetService {
})
if (!a) throw new Error('Asset not found')
let actualReplyToId = req.replyToId
let parentComment = null
if (req.replyToId) {
parentComment = await tx.assetComment.findUnique({
where: { id: req.replyToId },
include: { creator: true },
})
if (parentComment?.replyToId) {
actualReplyToId = parentComment.replyToId
}
}
const comment = await tx.assetComment.create({
data: {
assetId: a.id,
@@ -778,7 +790,7 @@ export class AssetService {
message: req.message,
annotation: req.annotations,
second: req.second,
replyToId: req.replyToId,
replyToId: actualReplyToId,
},
})
commentId = comment.id
@@ -797,12 +809,43 @@ export class AssetService {
}
}
// Detect bot mentions
const botMentionMatches = req.message.matchAll(/<@([^>]+)>/g)
for (const match of botMentionMatches) {
const agentId = match[1]
let foundAgent = false
// Parse bot mentions
const botMentionMatches = [...req.message.matchAll(/<@([^>]+)>/g)]
const mentionedAgentIds = new Set(botMentionMatches.map((match) => match[1]))
const handledAgentIds = new Set<string>()
if (parentComment && a.project) {
const rootSessionId = parentComment.sessionId
const isRootAgent = !!rootSessionId || parentComment.creator?.type === 'agent'
const rootAgentId = parentComment.creatorId
if (isRootAgent && rootAgentId) {
const explicitMention = mentionedAgentIds.has(rootAgentId)
await tx.workflowTask.create({
data: {
assetId: a.id,
type: 'chat',
status: 'pending',
teamId: a.project.team.id,
projectId: a.project.id,
payload: {
userCommentId: comment.id,
agentId: rootAgentId,
projectId: a.project.id,
sessionId: rootSessionId || undefined,
explicitMention,
},
},
})
handledAgentIds.add(rootAgentId)
}
}
// Handle any other explicitly mentioned agents
for (const agentId of mentionedAgentIds) {
if (handledAgentIds.has(agentId)) continue
let foundAgent = false
if (agentId === 'default') {
foundAgent = true
} else {
@@ -822,9 +865,11 @@ export class AssetService {
userCommentId: comment.id,
agentId: agentId,
projectId: a.project.id,
explicitMention: true,
},
},
})
handledAgentIds.add(agentId)
}
}
})
+8 -4
View File
@@ -124,6 +124,10 @@ export const MessageCard: React.FC<MessageCardProps> = ({
})
}
const preprocessMarkdown = (text: string): string => {
return text.replace(/<@([a-zA-Z0-9_-]+)>/g, '@$1').replace(/^\[([^\]]+)\]:/gm, '\\[$1\\]:')
}
const handleReply = () => {
onReply(message)
}
@@ -165,7 +169,7 @@ export const MessageCard: React.FC<MessageCardProps> = ({
</div>
) : message.sessionId ? (
<div className="text-sm leading-relaxed prose prose-sm dark:prose-invert max-w-none break-words">
<Markdown>{message.message!}</Markdown>
<Markdown>{preprocessMarkdown(message.message!)}</Markdown>
</div>
) : (
<div className="text-sm leading-relaxed whitespace-pre-wrap break-words text-wrap break-all">
@@ -371,7 +375,7 @@ export const MessageCard: React.FC<MessageCardProps> = ({
if (!content.trim()) return null
return (
<div className="text-xs text-foreground/80 dark:text-foreground/95 leading-relaxed prose prose-sm dark:prose-invert max-w-none break-words">
<Markdown>{content}</Markdown>
<Markdown>{preprocessMarkdown(content)}</Markdown>
</div>
)
}
@@ -389,7 +393,7 @@ export const MessageCard: React.FC<MessageCardProps> = ({
key={`str-${idx}`}
className="text-xs text-foreground/80 dark:text-foreground/95 leading-relaxed prose prose-sm dark:prose-invert max-w-none break-words"
>
<Markdown>{item}</Markdown>
<Markdown>{preprocessMarkdown(item)}</Markdown>
</div>,
)
return
@@ -406,7 +410,7 @@ export const MessageCard: React.FC<MessageCardProps> = ({
key={`txt-${idx}`}
className="text-xs text-foreground/80 dark:text-foreground/95 leading-relaxed prose prose-sm dark:prose-invert max-w-none break-words"
>
<Markdown>{text}</Markdown>
<Markdown>{preprocessMarkdown(text)}</Markdown>
</div>,
)
return
+21 -2
View File
@@ -35,7 +35,12 @@ type UploadingFile = {
interface ChatInputProps {
projectId: string
onSendMessage: (text: string, attachmentIds: string[], annotations?: Annotation[]) => void
onSendMessage: (
text: string,
attachmentIds: string[],
annotations?: Annotation[],
replyToId?: string | null,
) => void
replyingTo?: CommentInfo | null
onCancelReply?: () => void
users?: UserInfo[]
@@ -135,6 +140,20 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
}
}, [initialText])
// Focus editor when replyingTo becomes truthy
useEffect(() => {
if (replyingTo && editorRef.current) {
editorRef.current.focus()
// Focus and move cursor to end
const range = document.createRange()
const sel = window.getSelection()
range.selectNodeContents(editorRef.current)
range.collapse(false)
sel?.removeAllRanges()
sel?.addRange(range)
}
}, [replyingTo])
// Clean up drawing mode on unmount
useEffect(() => {
return () => {
@@ -376,7 +395,7 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
// Allow sending if annotations exist, even if text is empty
if (!processedText && successfulAttachmentIds.length === 0 && annotations.length === 0) return
onSendMessage(processedText, successfulAttachmentIds, annotations)
onSendMessage(processedText, successfulAttachmentIds, annotations, replyingTo?.id)
// Reset editor
editorRef.current.innerHTML = ''
@@ -52,6 +52,7 @@ export function FileViewerRightSidebar({
text: string
attachmentIds: string[]
annotations?: Annotation[]
replyToId?: string | null
} | null>(null)
const { data: apiFields } = useQuery({
@@ -126,6 +127,7 @@ export function FileViewerRightSidebar({
},
enabled: !!file?.id && (!isPublic || !!shareId),
initialPageParam: '',
refetchInterval: 2000,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getNextPageParam: (lastPage: any) => lastPage.pageInfo?.cursor || undefined,
})
@@ -135,11 +137,13 @@ export function FileViewerRightSidebar({
text,
attachmentIds,
annotations,
replyToId,
guestUserId,
}: {
text: string
attachmentIds: string[]
annotations?: Annotation[]
replyToId?: string | null
guestUserId?: string
}) => {
if (isPublic) {
@@ -150,7 +154,7 @@ export function FileViewerRightSidebar({
json: {
message: text,
attachmentIds: attachmentIds,
replyToId: replyingTo?.id,
replyToId: replyToId ?? undefined,
annotations: annotations,
},
},
@@ -169,7 +173,7 @@ export function FileViewerRightSidebar({
json: {
message: text,
attachmentIds: attachmentIds,
replyToId: replyingTo?.id,
replyToId: replyToId ?? undefined,
annotations: annotations,
},
})
@@ -220,6 +224,7 @@ export function FileViewerRightSidebar({
text: string,
attachmentIds: string[],
annotations?: Annotation[],
replyToId?: string | null,
) => {
if (!file?.id) return
@@ -235,16 +240,16 @@ export function FileViewerRightSidebar({
console.log('[handleSendMessage] guestUserId from storage:', guestUserId)
if (!guestUserId) {
console.log('[handleSendMessage] no guest ID, opening popup')
setPendingComment({ text, attachmentIds, annotations })
setPendingComment({ text, attachmentIds, annotations, replyToId })
setIsGuestPopupOpen(true)
return
}
createComment({ text, attachmentIds, annotations, guestUserId })
createComment({ text, attachmentIds, annotations, replyToId, guestUserId })
} else {
createComment({ text, attachmentIds, annotations })
createComment({ text, attachmentIds, annotations, replyToId })
}
} else {
createComment({ text, attachmentIds, annotations })
createComment({ text, attachmentIds, annotations, replyToId })
}
setReplyingTo(null)
}
+3 -5
View File
@@ -1,5 +1,4 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { setupTestDbHooks } from '@/db-test-hooks'
import { aiChatActivity } from './agent'
import { agentService } from '@/services/agent/agent'
@@ -10,13 +9,11 @@ vi.mock('@/services/agent/agent', () => ({
}))
describe('Agent Activities', () => {
setupTestDbHooks()
beforeEach(() => {
vi.clearAllMocks()
})
it('should call aiChatActivity', async () => {
it('should call aiChatActivity and delegate to agentService', async () => {
vi.mocked(agentService.chatWithAgent).mockResolvedValue({
text: 'AI response',
usage: { inputTokens: 1, outputTokens: 1, model: 'gpt-4' },
@@ -30,6 +27,7 @@ describe('Agent Activities', () => {
imageUrls: [],
projectId: 'p1',
folderId: 'f1',
sessionId: 'mock-session-id',
})
expect(agentService.chatWithAgent).toHaveBeenCalledWith(
@@ -38,7 +36,7 @@ describe('Agent Activities', () => {
'Hi',
[],
'',
undefined,
'mock-session-id',
undefined,
)
})
+5 -92
View File
@@ -1,6 +1,5 @@
import { agentService } from '@/services/agent/agent'
import type { AutofillField } from '@/agent'
import { prisma } from '@/db'
export interface AutofillAiParams {
teamId: string
@@ -21,108 +20,22 @@ export interface AiChatParams {
projectId: string
folderId: string
agentsInstruction?: string
sessionId?: string
sessionId: string
userId?: string
explicitMention?: boolean
}
export async function aiChatActivity(params: AiChatParams) {
const cleanMessage = params.message.replace(/<@[A-Z0-9]+>/g, '').trim()
const sessionId = params.sessionId
return agentService.chatWithAgent(
params.teamId,
params.agentId,
cleanMessage,
params.imageUrls,
params.agentsInstruction || '',
params.sessionId,
sessionId,
params.userId,
)
}
export interface CreateCommentParams {
assetId: string
message: string
sessionId?: string | null
agentId?: string | null
replyToId?: string | null
}
export async function createCommentActivity(params: CreateCommentParams) {
if (params.sessionId) {
const agentId = params.agentId && params.agentId !== 'default' ? params.agentId : 'default'
// Fetch teamId from asset
const asset = await prisma.asset.findUnique({
where: { id: params.assetId },
include: { project: true },
})
if (!asset || !asset.project) throw new Error('asset or project not found')
const teamId = asset.project.teamId
// Ensure user exists for agent
const userExists = await prisma.user.findUnique({ where: { id: agentId } })
if (!userExists) {
await prisma.user.create({
data: {
id: agentId,
name: 'Ai Agent',
email: `${agentId}@shumai.ai`,
type: 'agent',
},
})
}
// Ensure agent exists
const agentExists = await prisma.agent.findUnique({ where: { id: agentId } })
if (!agentExists) {
await prisma.agent.create({
data: {
id: agentId,
teamId,
type: 'chat',
config: {
provider: 'openai',
model: 'gpt-4',
},
},
})
}
// Ensure agent session exists
const sessionExists = await prisma.agentSession.findUnique({ where: { id: params.sessionId } })
if (!sessionExists) {
await prisma.agentSession.create({
data: {
id: params.sessionId,
agentId: agentId,
cwd: process.cwd(),
},
})
}
}
return prisma.assetComment.create({
data: {
assetId: params.assetId,
message: params.message,
sessionId: params.sessionId ?? null,
creatorId: params.agentId && params.agentId !== 'default' ? params.agentId : null,
replyToId: params.replyToId,
},
})
}
export interface UpdateCommentParams {
commentId: string
message: string
sessionId?: string | null
}
export async function updateCommentActivity(params: UpdateCommentParams) {
return prisma.assetComment.update({
where: { id: params.commentId },
data: {
message: params.message,
...(params.sessionId !== undefined ? { sessionId: params.sessionId } : {}),
},
})
}
+189
View File
@@ -0,0 +1,189 @@
import { describe, it, expect } from 'vitest'
import { setupTestDbHooks } from '@/db-test-hooks'
import { prisma } from '@/db'
import {
createCommentActivity,
updateCommentActivity,
deleteCommentActivity,
initializeAgentSessionActivity,
} from './db'
import type { SessionTreeEntry } from '@earendil-works/pi-agent-core'
describe('Database Activities', () => {
setupTestDbHooks()
it('should support comment CRUD activities (create, update, delete)', async () => {
const team = await prisma.team.create({ data: { name: 't1' } })
const user = await prisma.user.create({
data: { name: 'User One', email: 'user1@example.com' },
})
const project = await prisma.project.create({
data: { name: 'p1', teamId: team.id },
})
const file = await prisma.asset.create({
data: {
name: 'test-file',
type: 'file',
projectId: project.id,
creatorId: user.id,
status: 'uploaded',
},
})
// 1. Create Comment
const comment = await createCommentActivity({
assetId: file.id,
message: 'Initial comment',
})
expect(comment.id).toBeDefined()
expect(comment.message).toBe('Initial comment')
// 2. Update Comment
const updated = await updateCommentActivity({
commentId: comment.id,
message: 'Updated comment',
})
expect(updated.message).toBe('Updated comment')
// 3. Delete Comment
await deleteCommentActivity(comment.id)
const found = await prisma.assetComment.findUnique({
where: { id: comment.id },
})
expect(found).toBeNull()
})
it('should support multiple comments in the same session without violating unique session_id constraint', async () => {
const team = await prisma.team.create({ data: { name: 't2' } })
const user = await prisma.user.create({
data: { name: 'User Two', email: 'user2@example.com' },
})
const project = await prisma.project.create({
data: { name: 'p2', teamId: team.id },
})
const file = await prisma.asset.create({
data: {
name: 'test-file-2',
type: 'file',
projectId: project.id,
creatorId: user.id,
status: 'uploaded',
},
})
const sessionId = 'test-multi-comment-session'
// 1. Create first agent comment in the session
const c1 = await createCommentActivity({
assetId: file.id,
message: 'Agent comment 1',
sessionId,
agentId: 'default',
})
expect(c1.id).toBeDefined()
expect(c1.sessionId).toBe(sessionId)
// 2. Create second agent comment in the SAME session
const c2 = await createCommentActivity({
assetId: file.id,
message: 'Agent comment 2',
sessionId,
agentId: 'default',
})
expect(c2.id).toBeDefined()
expect(c2.sessionId).toBe(sessionId)
})
it('should initialize a new session with chronological context, prefixed usernames, and resolved user mentions', async () => {
const team = await prisma.team.create({ data: { name: 't1' } })
const user1 = await prisma.user.create({
data: { name: 'User One', email: 'user1@example.com' },
})
const user2 = await prisma.user.create({
data: { name: 'Matt', email: 'matt@example.com' },
})
const agentUser = await prisma.user.create({
data: { id: 'agent-user-id', name: 'Smart Agent', email: 'agent@example.com', type: 'agent' },
})
const project = await prisma.project.create({
data: { name: 'p1', teamId: team.id },
})
const file = await prisma.asset.create({
data: {
name: 'test-file',
type: 'file',
projectId: project.id,
creatorId: user1.id,
status: 'uploaded',
},
})
// Create existing comment 1 (User mentioning user2)
const comment1 = await prisma.assetComment.create({
data: {
assetId: file.id,
creatorId: user1.id,
message: `First comment message for <@${user2.id}>`,
},
})
// Create existing comment 1.5 (Agent)
const commentAgent = await prisma.assetComment.create({
data: {
assetId: file.id,
creatorId: agentUser.id,
message: 'I am helping',
},
})
// Create triggering comment 2 (Rule 1: no reply, mentions agent)
const comment2 = await prisma.assetComment.create({
data: {
assetId: file.id,
creatorId: user1.id,
message: 'Hello <@agent-user-id>',
},
})
const sessionId = await initializeAgentSessionActivity({
teamId: team.id,
agentId: 'agent-user-id',
userCommentId: comment2.id,
userId: user1.id,
})
expect(sessionId).toBeDefined()
// Verify session entries were populated with comment1 and commentAgent as context
const entries = await prisma.agentSessionEntry.findMany({
where: { sessionId },
orderBy: { id: 'asc' },
})
expect(entries.length).toBe(2)
// Verify User Comment Entry with resolved mention and username prefix
const entryData1 = entries[0].entry as unknown as SessionTreeEntry
expect(entryData1.id).toBeDefined()
expect(entryData1.id).not.toBe(comment1.id)
if (entryData1.type === 'message') {
const msg = entryData1.message as { role: 'user'; content: { type: 'text'; text: string }[] }
expect(msg.content[0].text).toBe('[User One]: First comment message for <@Matt>')
expect(msg.role).toBe('user')
} else {
throw new Error('Expected entry to be a message')
}
// Verify Agent Comment Entry
const entryData2 = entries[1].entry as unknown as SessionTreeEntry
expect(entryData2.id).toBeDefined()
expect(entryData2.id).not.toBe(commentAgent.id)
if (entryData2.type === 'message') {
const msg = entryData2.message as { role: 'user'; content: { type: 'text'; text: string }[] }
expect(msg.content[0].text).toBe('[Agent Message][Smart Agent]: I am helping')
expect(msg.role).toBe('user')
} else {
throw new Error('Expected entry to be a message')
}
})
})
+280
View File
@@ -0,0 +1,280 @@
import { prisma } from '@/db'
import type { AgentMessage, SessionTreeEntry } from '@earendil-works/pi-agent-core'
import { ulid } from 'ulid'
export interface InitializeAgentSessionParams {
teamId: string
agentId: string
userCommentId: string
userId?: string
}
export async function initializeAgentSessionActivity(
params: InitializeAgentSessionParams,
): Promise<string> {
const agentId = params.agentId === 'default' ? 'default' : params.agentId
// Ensure user exists for agent
const userExists = await prisma.user.findUnique({ where: { id: agentId } })
if (!userExists) {
await prisma.user.create({
data: {
id: agentId,
name: 'Ai Agent',
email: `${agentId}@shumai.ai`,
type: 'agent',
},
})
}
// Ensure agent exists
const agentExists = await prisma.agent.findUnique({ where: { id: agentId } })
if (!agentExists) {
await prisma.agent.create({
data: {
id: agentId,
teamId: params.teamId,
type: 'chat',
config: {
provider: 'openai',
model: 'gpt-4',
},
},
})
}
// Create a new AgentSession
const newSession = await prisma.agentSession.create({
data: {
agentId,
userId: params.userId || null,
cwd: process.cwd(),
},
})
const sessionId = newSession.id
// Fetch existing comments as context
let existingComments: Array<{
id: string
message: string | null
createdAt: Date
creatorId: string | null
creator: { type: string; name: string } | null
sessionId: string | null
}> = []
const userComment = await prisma.assetComment.findUnique({
where: { id: params.userCommentId },
include: { creator: true },
})
if (userComment) {
if (!userComment.replyToId) {
// Rule 1: outside of a reply, add all other comments on that asset
existingComments = await prisma.assetComment.findMany({
where: {
assetId: userComment.assetId,
id: { not: userComment.id },
},
orderBy: { id: 'asc' },
include: { creator: true },
})
} else {
// Rule 2: in a reply, add root comment + all other replies to it
const rootComment = await prisma.assetComment.findUnique({
where: { id: userComment.replyToId },
include: { creator: true },
})
if (rootComment) {
const replies = await prisma.assetComment.findMany({
where: {
replyToId: rootComment.id,
id: { not: userComment.id },
},
orderBy: { id: 'asc' },
include: { creator: true },
})
existingComments = [rootComment, ...replies]
}
}
}
// Resolve user mentions from IDs to names
const mentionRegex = /<@([^>]+)>/g
const mentionedUserIds = new Set<string>()
for (const c of existingComments) {
if (c.message) {
const matches = [...c.message.matchAll(mentionRegex)]
for (const match of matches) {
mentionedUserIds.add(match[1])
}
}
}
const userIdToNameMap = new Map<string, string>()
if (mentionedUserIds.size > 0) {
const resolvedUsers = await prisma.user.findMany({
where: {
id: { in: Array.from(mentionedUserIds) },
},
select: {
id: true,
name: true,
},
})
for (const u of resolvedUsers) {
if (u.name) {
userIdToNameMap.set(u.id, u.name)
}
}
}
// Save context as AgentSessionEntry records
let prevId: string | null = null
for (const c of existingComments) {
const isAgent = c.creator?.type === 'agent' || c.sessionId !== null
let messageContent = c.message || ''
// Replace <@USER_ID> with <@USER_NAME>
messageContent = messageContent.replace(mentionRegex, (match, userId) => {
const resolvedName = userIdToNameMap.get(userId)
return resolvedName ? `<@${resolvedName}>` : match
})
if (isAgent) {
const agentName = c.creator?.name || 'Ai Agent'
messageContent = `[Agent Message][${agentName}]: ${messageContent}`
} else if (c.creator?.name) {
messageContent = `[${c.creator.name}]: ${messageContent}`
}
const entryId = ulid()
const message: AgentMessage = {
role: 'user',
content: [{ type: 'text', text: messageContent }],
timestamp: c.createdAt.getTime(),
}
const entryJson: SessionTreeEntry = {
type: 'message',
id: entryId,
parentId: prevId,
timestamp: c.createdAt.toISOString(),
message,
}
await prisma.agentSessionEntry.create({
data: {
id: entryId,
sessionId,
entry: entryJson,
},
})
prevId = entryId
}
// Update leafId of the session
if (prevId) {
await prisma.agentSession.update({
where: { id: sessionId },
data: { leafId: prevId },
})
}
return sessionId
}
export async function deleteCommentActivity(commentId: string) {
return prisma.assetComment.delete({
where: { id: commentId },
})
}
export interface CreateCommentParams {
assetId: string
message: string
sessionId?: string | null
agentId?: string | null
replyToId?: string | null
}
export async function createCommentActivity(params: CreateCommentParams) {
if (params.sessionId) {
const agentId = params.agentId && params.agentId !== 'default' ? params.agentId : 'default'
// Fetch teamId from asset
const asset = await prisma.asset.findUnique({
where: { id: params.assetId },
include: { project: true },
})
if (!asset || !asset.project) throw new Error('asset or project not found')
const teamId = asset.project.teamId
// Ensure user exists for agent
const userExists = await prisma.user.findUnique({ where: { id: agentId } })
if (!userExists) {
await prisma.user.create({
data: {
id: agentId,
name: 'Ai Agent',
email: `${agentId}@shumai.ai`,
type: 'agent',
},
})
}
// Ensure agent exists
const agentExists = await prisma.agent.findUnique({ where: { id: agentId } })
if (!agentExists) {
await prisma.agent.create({
data: {
id: agentId,
teamId,
type: 'chat',
config: {
provider: 'openai',
model: 'gpt-4',
},
},
})
}
// Ensure agent session exists
const sessionExists = await prisma.agentSession.findUnique({ where: { id: params.sessionId } })
if (!sessionExists) {
await prisma.agentSession.create({
data: {
id: params.sessionId,
agentId: agentId,
cwd: process.cwd(),
},
})
}
}
return prisma.assetComment.create({
data: {
assetId: params.assetId,
message: params.message,
sessionId: params.sessionId ?? null,
creatorId: params.agentId && params.agentId !== 'default' ? params.agentId : null,
replyToId: params.replyToId,
},
})
}
export interface UpdateCommentParams {
commentId: string
message: string
sessionId?: string | null
}
export async function updateCommentActivity(params: UpdateCommentParams) {
return prisma.assetComment.update({
where: { id: params.commentId },
data: {
message: params.message,
...(params.sessionId !== undefined ? { sessionId: params.sessionId } : {}),
},
})
}
+2
View File
@@ -2,10 +2,12 @@ import * as taskActivities from './task'
import * as aiActivities from './ai'
import * as transcodeActivities from '@/transcode/activities/transcode'
import * as agentActivities from './agent'
import * as dbActivities from './db'
export const activities = {
...taskActivities,
...aiActivities,
...transcodeActivities,
...agentActivities,
...dbActivities,
}
+105
View File
@@ -31,6 +31,10 @@ describe('AIChat Workflow', () => {
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
_activityName: 'getAgentWorkerQueueActivity',
}),
deleteCommentActivity: Object.assign(vi.fn(), { _activityName: 'deleteCommentActivity' }),
initializeAgentSessionActivity: Object.assign(vi.fn(), {
_activityName: 'initializeAgentSessionActivity',
}),
}
beforeEach(() => {
@@ -48,6 +52,7 @@ describe('AIChat Workflow', () => {
},
)
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_worker_queue')
mockActivities.initializeAgentSessionActivity.mockResolvedValue('mock-session-id')
})
it('should process AI chat successfully', async () => {
@@ -219,4 +224,104 @@ describe('AIChat Workflow', () => {
output: { error: 'DB Down' },
})
})
it('should pass explicitMention payload parameter and format instruction when true', async () => {
const task: WorkflowTask = {
id: 'task-explicit',
assetId: 'asset-1',
type: WorkflowTaskType.chat,
status: WorkflowTaskStatus.pending,
output: null,
payload: {
userCommentId: 'comment-1',
agentId: 'bot-1',
explicitMention: true,
},
createdAt: new Date(),
updatedAt: new Date(),
heartbeat: null,
teamId: 'team-1',
projectId: 'proj-1',
uid: 'task-uid-explicit',
model: null,
inputTokens: 0,
outputTokens: 0,
}
mockActivities.getAssetActivity.mockResolvedValue({
id: 'asset-1',
project: { teamId: 'team-1', id: 'proj-1' },
})
mockActivities.getCommentActivity.mockResolvedValue({
id: 'comment-1',
message: 'Hello AI',
})
mockActivities.createCommentActivity.mockResolvedValue({
id: 'placeholder-1',
})
mockActivities.aiChatActivity.mockResolvedValue({
text: 'Hello Human',
usage: { inputTokens: 5, outputTokens: 5, model: 'gpt-4' },
})
await aiChat(task)
expect(mockActivities.aiChatActivity).toHaveBeenCalledWith(
expect.objectContaining({
explicitMention: true,
agentsInstruction: expect.stringContaining('MUST reply to this message'),
}),
)
})
it('should delete placeholder comment when AI response is __NO_REPLY__', async () => {
const task: WorkflowTask = {
id: 'task-no-reply',
assetId: 'asset-1',
type: WorkflowTaskType.chat,
status: WorkflowTaskStatus.pending,
output: null,
payload: {
userCommentId: 'comment-1',
agentId: 'bot-1',
explicitMention: false,
},
createdAt: new Date(),
updatedAt: new Date(),
heartbeat: null,
teamId: 'team-1',
projectId: 'proj-1',
uid: 'task-uid-no-reply',
model: null,
inputTokens: 0,
outputTokens: 0,
}
mockActivities.getAssetActivity.mockResolvedValue({
id: 'asset-1',
project: { teamId: 'team-1', id: 'proj-1' },
})
mockActivities.getCommentActivity.mockResolvedValue({
id: 'comment-1',
message: 'Hello AI',
})
mockActivities.createCommentActivity.mockResolvedValue({
id: 'placeholder-delete-me',
})
mockActivities.aiChatActivity.mockResolvedValue({
text: ' __NO_REPLY__ ',
usage: { inputTokens: 5, outputTokens: 5, model: 'gpt-4' },
})
await aiChat(task)
expect(mockActivities.deleteCommentActivity).toHaveBeenCalledWith('placeholder-delete-me')
expect(mockActivities.updateCommentActivity).not.toHaveBeenCalled()
})
})
+38 -16
View File
@@ -1,9 +1,9 @@
import type { WorkflowTask } from '@/generated/prisma/client'
import {
getActivities,
executeActivity,
TaskQueueDb,
getActivities,
TaskQueueAgent,
TaskQueueDb,
} from '@/workflow/workflow-utils'
export async function aiChat(task: WorkflowTask): Promise<void> {
@@ -16,6 +16,8 @@ export async function aiChat(task: WorkflowTask): Promise<void> {
updateCommentActivity,
updateTaskUsageActivity,
getAgentWorkerQueueActivity,
deleteCommentActivity,
initializeAgentSessionActivity,
} = getActivities()
let placeholderCommentId: string | undefined
@@ -30,6 +32,8 @@ export async function aiChat(task: WorkflowTask): Promise<void> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const payload = task.payload as any
let sessionId = payload?.sessionId || payload?.session_id
// 1. Get User Comment
const userCommentId = payload?.userCommentId
if (!userCommentId) throw new Error('userCommentId missing in payload')
@@ -40,7 +44,7 @@ export async function aiChat(task: WorkflowTask): Promise<void> {
const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, {
assetId: task.assetId,
message: '__CHAT__',
sessionId: payload?.session_id || 'pending',
sessionId: sessionId || 'pending',
agentId: payload?.agentId,
replyToId: userComment.replyToId ?? userComment.id,
})
@@ -53,7 +57,17 @@ export async function aiChat(task: WorkflowTask): Promise<void> {
}
const teamId = asset.project.teamId
// 4. Prepare Images (Attachments only)
// 4. Initialize Session if missing (Database Activity on db_queue)
if (!sessionId) {
sessionId = await executeActivity(TaskQueueDb, initializeAgentSessionActivity, {
teamId,
agentId: payload.agentId,
userCommentId,
userId: payload.userId,
})
}
// 5. Prepare Images (Attachments only)
const attachmentImageUrls: string[] = []
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const userCommentWithAttachments = userComment as any
@@ -73,7 +87,13 @@ export async function aiChat(task: WorkflowTask): Promise<void> {
instruction += `\n\nIf you need to view the asset's media content (frames/images/video), call the 'analyze_asset_media' tool by passing the appropriate 'key' from the Asset Media Info above. Choose the most suitable format based on your capabilities and the user's request (e.g., use a poster or sprite for quick visual checks, or a transcode/raw file for detailed analysis).`
// 5. Call AI Chat
if (payload?.explicitMention) {
instruction += `\n\nThe user explicitly mentioned you in their message. You MUST reply to this message.`
} else {
instruction += `\n\nThe user did not explicitly mention you, but is replying in a thread where you are the participant. Let's decide if you should reply or not. If the user is not directly addressing you or doesn't need a response from you, you may choose to not reply. To choose not to reply, respond with exactly and only the text: __NO_REPLY__.`
}
// 6. Call AI Chat
let folderId = ''
if (asset.type === 'folder') {
folderId = asset.id
@@ -91,23 +111,25 @@ export async function aiChat(task: WorkflowTask): Promise<void> {
projectId: payload.projectId,
folderId,
agentsInstruction: instruction,
sessionId: payload.session_id,
sessionId,
userId: payload.userId,
explicitMention: payload?.explicitMention,
})
// 6. Update Placeholder Comment
// 7. Update Placeholder Comment
if (placeholderCommentId) {
await executeActivity(TaskQueueDb, updateCommentActivity, {
commentId: placeholderCommentId,
message: aiResult.text,
sessionId: aiResult.sessionId,
})
// Also store sessionId in comment's metadata if we had such a field,
// but for now we just return it in task status.
if (aiResult.text.trim() === '__NO_REPLY__') {
await executeActivity(TaskQueueDb, deleteCommentActivity, placeholderCommentId)
} else {
await executeActivity(TaskQueueDb, updateCommentActivity, {
commentId: placeholderCommentId,
message: aiResult.text,
sessionId: aiResult.sessionId,
})
}
}
// 7. Update Usage
// 8. Update Usage
if (aiResult.usage) {
await executeActivity(TaskQueueDb, updateTaskUsageActivity, {
taskId: task.id,