Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

5.0 KB
Raw Blame
import { isNotNull, isNull } from 'drizzle-orm';
import { boolean, index, integer, pgTable, text, uniqueIndex, varchar } from 'drizzle-orm/pg-core';
import { createInsertSchema } from 'drizzle-zod';
import { z } from 'zod';

import { idGenerator, randomSlug } from '../utils/idGenerator';
import { softDeleteColumns, timestamps } from './_helpers';
import { users } from './user';
import { workspaces } from './workspace';

/** Session-group visibility β€” shared by column def and insert schema. */
export const SESSION_GROUP_VISIBILITY = ['private', 'public'] as const;

/** Session type β€” shared by column def and insert schema. */
export const SESSION_TYPE = ['agent', 'group'] as const;

//  ======= sessionGroups ======= //

export const sessionGroups = pgTable(
  'session_groups',
  {
    id: text('id')
      .$defaultFn(() => idGenerator('sessionGroups'))
      .primaryKey(),
    name: text('name').notNull(),
    sort: integer('sort'),

    userId: text('user_id')
      .references(() => users.id, { onDelete: 'cascade' })
      .notNull(),

    clientId: text('client_id'),
    workspaceId: text('workspace_id').references(() => workspaces.id, { onDelete: 'cascade' }),

    /**
     * Visibility within the owning workspace. `public` (default) means every
     * workspace member can see the folder; `private` constrains it to the
     * creator (`user_id`). Ignored in personal mode.
     */
    visibility: text('visibility', { enum: SESSION_GROUP_VISIBILITY }).default('public').notNull(),

    /** Recycle bin β€” see `schemas/trash.ts`. */
    ...softDeleteColumns(),
    ...timestamps,
  },
  (table) => ({
    clientIdUnique: uniqueIndex('session_groups_client_id_user_id_unique').on(
      table.clientId,
      table.userId,
    ),
    userIdIdx: index('session_groups_user_id_idx').on(table.userId),
    workspaceIdIdx: index('session_groups_workspace_id_idx').on(table.workspaceId),
    workspaceVisibilityIdx: index('session_groups_workspace_visibility_idx').on(
      table.workspaceId,
      table.visibility,
      table.userId,
    ),
  }),
);

// Explicit z.enum overrides: drizzle-zod + Zod 4 maps text(..., { enum }) to a
// ZodEnum whose inferred output pollutes with String prototype members
// (e.g. `"private" | "public" | 2 | (() => string) | ...`), which breaks
// assignability to Drizzle `$inferSelect` partials used by model.update.
// Keep `.optional()` so defaulted columns stay omit-able (bare z.enum would
// make them required and change runtime insert validation).
// Enum values from SESSION_GROUP_VISIBILITY so column def and schema stay in sync.
export const insertSessionGroupSchema = createInsertSchema(sessionGroups, {
  visibility: z.enum(SESSION_GROUP_VISIBILITY).optional(),
});

export type NewSessionGroup = typeof sessionGroups.$inferInsert;
export type SessionGroupItem = typeof sessionGroups.$inferSelect;

//  ======= sessions ======= //

/**
 * @deprecated Legacy 1:1 shell around an agent, kept only for rows that
 * pre-date agent-native topics (`topics.agent_id`) and for the mobile session
 * list. New code addresses conversations by `agents` / `topics` and must not
 * write here. Not recycle-bin aware on purpose: the agent is the restorable
 * unit β€” a trashed agent hides its session through the agent join, and the
 * session row is hard-deleted with the agent at purge time.
 */
export const sessions = pgTable(
  'sessions',
  {
    id: text('id')
      .$defaultFn(() => idGenerator('sessions'))
      .primaryKey(),
    slug: varchar('slug', { length: 100 })
      .notNull()
      .$defaultFn(() => randomSlug()),
    title: text('title'),
    description: text('description'),
    avatar: text('avatar'),
    backgroundColor: text('background_color'),

    type: text('type', { enum: SESSION_TYPE }).default('agent'),

    userId: text('user_id')
      .references(() => users.id, { onDelete: 'cascade' })
      .notNull(),
    groupId: text('group_id').references(() => sessionGroups.id, { onDelete: 'set null' }),
    clientId: text('client_id'),
    pinned: boolean('pinned').default(false),
    workspaceId: text('workspace_id').references(() => workspaces.id, { onDelete: 'cascade' }),

    ...timestamps,
  },
  (t) => [
    uniqueIndex('slug_user_id_unique').on(t.slug, t.userId).where(isNull(t.workspaceId)),
    uniqueIndex('sessions_client_id_user_id_unique').on(t.clientId, t.userId),

    index('sessions_user_id_idx').on(t.userId),
    index('sessions_id_user_id_idx').on(t.id, t.userId),
    index('sessions_user_id_updated_at_idx').on(t.userId, t.updatedAt),
    index('sessions_group_id_idx').on(t.groupId),
    index('sessions_workspace_id_idx').on(t.workspaceId),
    uniqueIndex('sessions_slug_workspace_id_unique')
      .on(t.workspaceId, t.slug)
      .where(isNotNull(t.workspaceId)),
  ],
);

export const insertSessionSchema = createInsertSchema(sessions, {
  // column is nullable + default β€” match drizzle-zod insert optionality
  type: z.enum(SESSION_TYPE).nullish(),
});
// export const selectSessionSchema = createSelectSchema(sessions);

export type NewSession = typeof sessions.$inferInsert;
export type SessionItem = typeof sessions.$inferSelect;