make meeting creation user level

This commit is contained in:
2026-06-18 04:55:25 +02:00
parent 05740e122e
commit 85af4aec77
9 changed files with 167 additions and 167 deletions

View File

@@ -0,0 +1,25 @@
'use server'
import { getGoogleCalendarClient, getGoogleCalendarId } from '~/server/googleCalendar'
export async function cancelMeeting({ eventId }: { eventId: string }) {
try {
const calendar = getGoogleCalendarClient()
await calendar.events.delete({
calendarId: getGoogleCalendarId(),
eventId,
})
return {
success: true,
eventId,
message: 'Meeting removed from Gregor availability calendar.',
}
} catch (error) {
console.error('Failed to cancel meeting:', error)
return {
success: false,
error: 'Failed to remove the meeting from Gregor availability calendar.',
}
}
}

View File

@@ -1,7 +1,34 @@
'use server' 'use server'
import { clerkClient, auth } from '@clerk/nextjs/server'
import { google } from 'googleapis'
import { env } from '~/env' import { env } from '~/env'
import { getGoogleCalendarClient, getGoogleCalendarId } from '~/server/googleCalendar'
function googleCalendarDate(date: Date) {
return date.toISOString().replace(/[-:]|\.\d{3}/g, '')
}
function createGoogleCalendarTemplateLink({
title,
description,
startTime,
endTime,
gregorEmail,
}: {
title: string
description: string
startTime: Date
endTime: Date
gregorEmail: string
}) {
const params = new URLSearchParams({
action: 'TEMPLATE',
text: title,
dates: `${googleCalendarDate(startTime)}/${googleCalendarDate(endTime)}`,
details: description,
add: gregorEmail,
})
return `https://calendar.google.com/calendar/render?${params.toString()}`
}
export async function scheduleMeeting({ export async function scheduleMeeting({
title, title,
@@ -19,59 +46,39 @@ export async function scheduleMeeting({
attendeeName?: string attendeeName?: string
}) { }) {
try { try {
const clerk = await clerkClient() const calendar = getGoogleCalendarClient()
const userAuth = await auth()
const user = await clerk.users.getUser(userAuth.userId?userAuth.userId:"")
// Get admin's Google OAuth token to create the event on Gregor's calendar
const adminTokenResponse = await clerk.users.getUserOauthAccessToken(
env.ADMIN_USER_CLERK_ID,
'oauth_google',
)
const adminToken = adminTokenResponse.data[0]
if (!adminToken?.token) {
return { success: false, error: 'Admin Google Calendar not connected. Ensure the admin account is linked with Google and has calendar scope enabled.' }
}
// Try to resolve visitor's Google email for the invite
let visitorEmail: string | undefined = attendeeEmail
if (!visitorEmail) {
visitorEmail = user?.emailAddresses.at(0)?.emailAddress ?? undefined
}
const oAuth2Client = new google.auth.OAuth2()
oAuth2Client.setCredentials({ access_token: adminToken.token })
const calendar = google.calendar({ version: 'v3', auth: oAuth2Client })
const startTime = new Date(dateTime) const startTime = new Date(dateTime)
const endTime = new Date(startTime.getTime() + durationMinutes * 60 * 1000) const endTime = new Date(startTime.getTime() + durationMinutes * 60 * 1000)
const attendeeNote = attendeeEmail
? `\n\nVisitor: ${attendeeName ?? 'Unknown'} <${attendeeEmail}>`
: ''
const eventDescription = `${description}${attendeeNote}`
const attendees: { email: string; displayName?: string }[] = [] const eventRequest = {
if (visitorEmail) {
attendees.push({ email: visitorEmail, displayName: attendeeName })
}
const event = await calendar.events.insert({
calendarId: 'primary',
sendUpdates: 'all',
requestBody: {
summary: title, summary: title,
description, description: eventDescription,
start: { dateTime: startTime.toISOString(), timeZone: 'UTC' }, start: { dateTime: startTime.toISOString(), timeZone: 'UTC' },
end: { dateTime: endTime.toISOString(), timeZone: 'UTC' }, end: { dateTime: endTime.toISOString(), timeZone: 'UTC' },
attendees, }
}, const event = await calendar.events.insert({
sendNotifications: true calendarId: getGoogleCalendarId(),
requestBody: eventRequest,
}) })
const inviteLink = event.data.htmlLink ?? undefined const addToCalendarLink = createGoogleCalendarTemplateLink({
title,
description,
startTime,
endTime,
gregorEmail: env.GREGOR_MEETING_EMAIL,
})
return { return {
success: true, success: true,
eventId: event.data.id, eventId: event.data.id,
htmlLink: inviteLink, addToCalendarLink,
inviteLink, message: `Meeting "${title}" scheduled for ${startTime.toLocaleString()}.${attendeeEmail ? ` Visitor email noted: ${attendeeEmail}.` : ''} The add-to-calendar link invites ${env.GREGOR_MEETING_EMAIL}.`,
message: `Meeting "${title}" scheduled for ${startTime.toLocaleString()}${visitorEmail ? `. Invite sent to ${visitorEmail}.` : '.'}${inviteLink ? ` Calendar invite: ${inviteLink}` : ''}`,
} }
} catch (error) { } catch (error) {
console.error('Failed to schedule meeting:', error) console.error('Failed to schedule meeting:', error)

View File

@@ -36,7 +36,9 @@ Runtime context:
- Current server time: ${new Date().toISOString()}. - Current server time: ${new Date().toISOString()}.
- Default meeting timezone: Europe/Berlin. - Default meeting timezone: Europe/Berlin.
- For availability questions like "next open spot", call getAvailability once. It defaults to checking from now. Use nextAvailableSlot for the next opening, or the first item in availableSlots if needed. Do not call getAvailability again just to get more slots. - For availability questions like "next open spot", call getAvailability once. It defaults to checking from now. Use nextAvailableSlot for the next opening, or the first item in availableSlots if needed. Do not call getAvailability again just to get more slots.
- After scheduleMeeting succeeds, include the returned inviteLink or htmlLink in your response. - After scheduleMeeting succeeds, include only the returned addToCalendarLink for the visitor. Format it as a Markdown link like [Add this meeting to your Google Calendar](URL); do not paste the raw URL. Explain briefly that this link lets them add the meeting to their own calendar and invite Gregor. Do not mention internal Google Calendar event links.
- You can remove meetings from Gregor's availability calendar with cancelMeeting only when you have the exact eventId from a previous scheduleMeeting result. If a visitor asks to reschedule and you have both the old eventId and a confirmed new slot, call cancelMeeting once for the old event and scheduleMeeting once for the new event. If you do not have the old eventId, ask for clarification instead of guessing.
- When rescheduling, make clear that cancelMeeting only removes the old slot from Gregor's availability calendar. If the visitor already added the old link to their own calendar, they may need to remove that copy themselves.
- Do not calculate or invent calendar availability yourself.` - Do not calculate or invent calendar availability yourself.`
const model = await servTrpc.chat.getModel() const model = await servTrpc.chat.getModel()
@@ -57,7 +59,7 @@ Runtime context:
system: systemPrompt, system: systemPrompt,
messages: await convertToModelMessages(messages), messages: await convertToModelMessages(messages),
tools: createChatTools(), tools: createChatTools(),
stopWhen: stepCountIs(2), stopWhen: stepCountIs(3),
onFinish: async ({ text, finishReason }) => { onFinish: async ({ text, finishReason }) => {
console.log('[ai:chat:onFinish]', { console.log('[ai:chat:onFinish]', {
finishReason, finishReason,

View File

@@ -11,6 +11,8 @@ function toolLabel(type: string) {
return "Loading project details"; return "Loading project details";
case "tool-getAvailability": case "tool-getAvailability":
return "Checking availability"; return "Checking availability";
case "tool-cancelMeeting":
return "Removing meeting";
case "tool-getCurrentUnixTime": case "tool-getCurrentUnixTime":
return "Checking current time"; return "Checking current time";
default: default:
@@ -27,7 +29,7 @@ export const AssistantMessage = (props: { message: UIMessage }) => {
> >
<div <div
className= className=
'max-w-[80%] px-4 py-2 text-sm space-y-2 bg-muted' 'max-w-[80%] min-w-0 px-4 py-2 text-sm space-y-2 bg-muted break-words [overflow-wrap:anywhere] [&_a]:break-all [&_pre]:max-w-full [&_pre]:overflow-x-auto'
> >
{message.parts.map((part, i) => { {message.parts.map((part, i) => {
if (part.type === 'text') { if (part.type === 'text') {
@@ -40,7 +42,7 @@ export const AssistantMessage = (props: { message: UIMessage }) => {
type: 'tool-scheduleMeeting' type: 'tool-scheduleMeeting'
state: string state: string
input: unknown input: unknown
output?: { success: boolean; message?: string; htmlLink?: string; inviteLink?: string; error?: string } output?: { success: boolean; error?: string }
} }
if (toolPart.state === 'input-available' || toolPart.state === 'input-streaming') { if (toolPart.state === 'input-available' || toolPart.state === 'input-streaming') {
return ( return (
@@ -51,26 +53,32 @@ export const AssistantMessage = (props: { message: UIMessage }) => {
} }
if (toolPart.state === 'output-available' && toolPart.output) { if (toolPart.state === 'output-available' && toolPart.output) {
const result = toolPart.output const result = toolPart.output
const inviteLink = result.inviteLink ?? result.htmlLink if (result.success) return null
return ( return (
<div key={i} className="text-xs mt-1 p-2 bg-background/20 rounded"> <div key={i} className="text-xs mt-1 p-2 bg-background/20 rounded">
{result.success ? (
<span>
{result.message}{' '}
{inviteLink && (
<a
href={inviteLink}
target="_blank"
rel="noopener noreferrer"
className="underline"
>
Open calendar invite
</a>
)}
</span>
) : (
<span> {result.error}</span> <span> {result.error}</span>
)} </div>
)
}
}
if (part.type === 'tool-cancelMeeting') {
const toolPart = part as unknown as {
type: 'tool-cancelMeeting'
state: string
output?: { success: boolean; error?: string }
}
if (toolPart.state === 'input-available' || toolPart.state === 'input-streaming') {
return (
<p key={i} className="text-xs opacity-70 italic">
Removing meeting
</p>
)
}
if (toolPart.state === 'output-available' && toolPart.output) {
if (toolPart.output.success) return null
return (
<div key={i} className="text-xs mt-1 p-2 bg-background/20 rounded">
<span> {toolPart.output.error}</span>
</div> </div>
) )
} }

View File

@@ -14,7 +14,7 @@ export const UserMessage = (props:{message: UIMessage}) => {
> >
<div <div
className= className=
'max-w-[80%] px-4 py-2 text-sm space-y-2 bg-primary' 'max-w-[80%] min-w-0 px-4 py-2 text-sm space-y-2 bg-primary break-words whitespace-pre-wrap [overflow-wrap:anywhere]'
> >
{message} {message}
</div> </div>

View File

@@ -100,12 +100,19 @@ function PullQuote({ children }: { children: ReactNode }) {
} }
function ExternalLink(props: ComponentPropsWithoutRef<"a">) { function ExternalLink(props: ComponentPropsWithoutRef<"a">) {
const href = props.href ?? ""; const { className, ...rest } = props;
const isExternal = /^https?:\/\//.test(href);
if (!isExternal) return <a {...props} />; return (
<a
return <a {...props} target="_blank" rel="noreferrer" />; {...rest}
target="_blank"
rel="noreferrer"
className={cn(
"text-sky-600 underline underline-offset-4 hover:text-sky-700 dark:text-sky-400 dark:hover:text-sky-300",
className,
)}
/>
);
} }
const blockComponents = new Set<unknown>([Callout, Figure, PullQuote, TagList]); const blockComponents = new Set<unknown>([Callout, Figure, PullQuote, TagList]);

View File

@@ -31,6 +31,10 @@ export const env = createEnv({
CLERK_SECRET_KEY: z.string(), CLERK_SECRET_KEY: z.string(),
ADMIN_USER_CLERK_ID: z.string(), ADMIN_USER_CLERK_ID: z.string(),
OPENAI_API_KEY: z.string(), OPENAI_API_KEY: z.string(),
GOOGLE_SERVICE_ACCOUNT_EMAIL: z.string().email(),
GOOGLE_SERVICE_ACCOUNT_PRIVATE_KEY: z.string(),
GOOGLE_CALENDAR_ID: z.string(),
GREGOR_MEETING_EMAIL: z.string().email(),
NODE_ENV: z NODE_ENV: z
.enum(["development", "test", "production"]) .enum(["development", "test", "production"])
.default("development"), .default("development"),
@@ -72,6 +76,10 @@ export const env = createEnv({
POSTGRES_PRISMA_URL: process.env.POSTGRES_PRISMA_URL, POSTGRES_PRISMA_URL: process.env.POSTGRES_PRISMA_URL,
ADMIN_USER_CLERK_ID: process.env.ADMIN_USER_CLERK_ID, ADMIN_USER_CLERK_ID: process.env.ADMIN_USER_CLERK_ID,
OPENAI_API_KEY: process.env.OPENAI_API_KEY, OPENAI_API_KEY: process.env.OPENAI_API_KEY,
GOOGLE_SERVICE_ACCOUNT_EMAIL: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL,
GOOGLE_SERVICE_ACCOUNT_PRIVATE_KEY: process.env.GOOGLE_SERVICE_ACCOUNT_PRIVATE_KEY,
GOOGLE_CALENDAR_ID: process.env.GOOGLE_CALENDAR_ID,
GREGOR_MEETING_EMAIL: process.env.GREGOR_MEETING_EMAIL,
NEXT_PUBLIC_ADMIN_USER_CLERK_ID: process.env.NEXT_PUBLIC_ADMIN_USER_CLERK_ID, NEXT_PUBLIC_ADMIN_USER_CLERK_ID: process.env.NEXT_PUBLIC_ADMIN_USER_CLERK_ID,
CLERK_SECRET_KEY: process.env.CLERK_SECRET_KEY, CLERK_SECRET_KEY: process.env.CLERK_SECRET_KEY,
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY, NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY,

View File

@@ -1,14 +1,13 @@
import "server-only"; import "server-only";
import { clerkClient } from "@clerk/nextjs/server";
import { tool } from "ai"; import { tool } from "ai";
import { desc } from "drizzle-orm"; import { desc } from "drizzle-orm";
import { google } from "googleapis";
import { z } from "zod"; import { z } from "zod";
import { cancelMeeting } from "~/app/actions/cancelMeeting";
import { scheduleMeeting } from "~/app/actions/scheduleMeeting"; import { scheduleMeeting } from "~/app/actions/scheduleMeeting";
import { env } from "~/env";
import { db } from "~/server/db"; import { db } from "~/server/db";
import { blogPost, music } from "~/server/dbschema/schema"; import { blogPost, music } from "~/server/dbschema/schema";
import { getGoogleCalendarClient, getGoogleCalendarId } from "~/server/googleCalendar";
const contentTypeSchema = z.enum(["cv", "project", "blog", "music"]); const contentTypeSchema = z.enum(["cv", "project", "blog", "music"]);
@@ -25,9 +24,6 @@ type SearchResult = {
type ProjectWithStack = Awaited<ReturnType<typeof loadProjects>>[number]; type ProjectWithStack = Awaited<ReturnType<typeof loadProjects>>[number];
let cachedAdminGoogleToken: { token: string; expiresAt: number } | undefined;
let adminGoogleTokenRequest: Promise<string | undefined> | undefined;
function stripMarkup(value: string | null | undefined) { function stripMarkup(value: string | null | undefined) {
return (value ?? "") return (value ?? "")
.replace(/```[\s\S]*?```/g, " ") .replace(/```[\s\S]*?```/g, " ")
@@ -364,83 +360,6 @@ function logAvailability(requestId: string, message: string, data?: Record<strin
console.log(`[ai:getAvailability:${requestId}] ${message}`, data ?? ""); console.log(`[ai:getAvailability:${requestId}] ${message}`, data ?? "");
} }
function withTimeout<T>(promise: Promise<T>, timeoutMs: number, message: string) {
return Promise.race([
promise,
new Promise<T>((_, reject) => {
setTimeout(() => reject(new Error(message)), timeoutMs);
}),
]);
}
async function getAdminGoogleToken(requestId: string) {
if (cachedAdminGoogleToken && cachedAdminGoogleToken.expiresAt > Date.now()) {
logAvailability(requestId, "admin oauth token cache hit");
return cachedAdminGoogleToken.token;
}
if (!adminGoogleTokenRequest) {
adminGoogleTokenRequest = (async () => {
logAvailability(requestId, "admin oauth token request start");
const clerk = await clerkClient();
const adminTokenResponse = await clerk.users.getUserOauthAccessToken(
env.ADMIN_USER_CLERK_ID,
"oauth_google",
);
const token = adminTokenResponse.data[0]?.token;
if (token) {
cachedAdminGoogleToken = {
token,
expiresAt: Date.now() + 5 * 60 * 1000,
};
}
return token;
})().finally(() => {
adminGoogleTokenRequest = undefined;
});
} else {
logAvailability(requestId, "admin oauth token request joined");
}
return withTimeout(
adminGoogleTokenRequest,
5000,
"Timed out while loading the admin Google OAuth token.",
);
}
async function getAdminCalendar(requestId: string) {
let adminToken: string | undefined;
try {
adminToken = await getAdminGoogleToken(requestId);
} catch (error) {
console.error(`[ai:getAvailability:${requestId}] admin oauth token failed`, error);
return {
success: false as const,
error: "Timed out while loading Gregor's Google Calendar connection.",
};
}
logAvailability(requestId, "admin oauth token resolved", {
hasToken: Boolean(adminToken),
});
if (!adminToken) {
return {
success: false as const,
error: "Admin Google Calendar is not connected or does not expose a Google OAuth token.",
};
}
const oAuth2Client = new google.auth.OAuth2();
oAuth2Client.setCredentials({ access_token: adminToken });
return {
success: true as const,
calendar: google.calendar({ version: "v3", auth: oAuth2Client }),
};
}
export function createChatTools() { export function createChatTools() {
return { return {
scheduleMeeting: tool({ scheduleMeeting: tool({
@@ -474,6 +393,13 @@ export function createChatTools() {
return scheduleMeeting({ ...input }); return scheduleMeeting({ ...input });
}, },
}), }),
cancelMeeting: tool({
description: "Remove a previously scheduled meeting from Gregor's dedicated availability calendar. Use only when you have the exact eventId returned by scheduleMeeting.",
inputSchema: z.object({
eventId: z.string().min(1).describe("Google Calendar event id returned by a previous scheduleMeeting tool call."),
}),
execute: async ({ eventId }) => cancelMeeting({ eventId }),
}),
searchSiteContent: tool({ searchSiteContent: tool({
description: "Search Gregor Lohaus's own website content across CV entries, projects, blog posts, and music. Use this for questions about Gregor's work, skills, writing, projects, or site content. For broad questions about Gregor's projects, use types ['project'] so the tool returns the project catalog.", description: "Search Gregor Lohaus's own website content across CV entries, projects, blog posts, and music. Use this for questions about Gregor's work, skills, writing, projects, or site content. For broad questions about Gregor's projects, use types ['project'] so the tool returns the project catalog.",
inputSchema: z.object({ inputSchema: z.object({
@@ -589,27 +515,24 @@ export function createChatTools() {
rangeEnd: rangeEnd.toISOString(), rangeEnd: rangeEnd.toISOString(),
}); });
const adminCalendar = await getAdminCalendar(requestId); const calendar = getGoogleCalendarClient();
const calendarId = getGoogleCalendarId();
if (!adminCalendar.success) { logAvailability(requestId, "service account calendar ready", {
logAvailability(requestId, "admin calendar unavailable", { calendarId,
error: adminCalendar.error,
}); });
return adminCalendar;
}
let busy: Array<{ start: Date; end: Date }>; let busy: Array<{ start: Date; end: Date }>;
try { try {
logAvailability(requestId, "freebusy request"); logAvailability(requestId, "freebusy request");
const response = await adminCalendar.calendar.freebusy.query({ const response = await calendar.freebusy.query({
requestBody: { requestBody: {
timeMin: rangeStart.toISOString(), timeMin: rangeStart.toISOString(),
timeMax: rangeEnd.toISOString(), timeMax: rangeEnd.toISOString(),
timeZone, timeZone,
items: [{ id: "primary" }], items: [{ id: calendarId }],
}, },
}); });
busy = (response.data.calendars?.["primary"]?.busy ?? []) busy = (response.data.calendars?.[calendarId]?.busy ?? [])
.map((item) => ({ .map((item) => ({
start: parseDate(item.start ?? undefined, rangeStart), start: parseDate(item.start ?? undefined, rangeStart),
end: parseDate(item.end ?? undefined, rangeStart), end: parseDate(item.end ?? undefined, rangeStart),

View File

@@ -0,0 +1,20 @@
import "server-only";
import { google } from "googleapis";
import { env } from "~/env";
const calendarScope = "https://www.googleapis.com/auth/calendar";
export function getGoogleCalendarClient() {
const auth = new google.auth.JWT({
email: env.GOOGLE_SERVICE_ACCOUNT_EMAIL,
key: env.GOOGLE_SERVICE_ACCOUNT_PRIVATE_KEY.replace(/\\n/g, "\n"),
scopes: [calendarScope],
});
return google.calendar({ version: "v3", auth });
}
export function getGoogleCalendarId() {
return env.GOOGLE_CALENDAR_ID;
}