1 Commits

Author SHA1 Message Date
85af4aec77 make meeting creation user level 2026-06-18 04:55:25 +02:00
11 changed files with 169 additions and 169 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'
import { clerkClient, auth } from '@clerk/nextjs/server'
import { google } from 'googleapis'
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({
title,
@@ -19,59 +46,39 @@ export async function scheduleMeeting({
attendeeName?: string
}) {
try {
const clerk = await clerkClient()
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 calendar = getGoogleCalendarClient()
const startTime = new Date(dateTime)
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 }[] = []
if (visitorEmail) {
attendees.push({ email: visitorEmail, displayName: attendeeName })
const eventRequest = {
summary: title,
description: eventDescription,
start: { dateTime: startTime.toISOString(), timeZone: 'UTC' },
end: { dateTime: endTime.toISOString(), timeZone: 'UTC' },
}
const event = await calendar.events.insert({
calendarId: 'primary',
sendUpdates: 'all',
requestBody: {
summary: title,
description,
start: { dateTime: startTime.toISOString(), timeZone: 'UTC' },
end: { dateTime: endTime.toISOString(), timeZone: 'UTC' },
attendees,
},
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 {
success: true,
eventId: event.data.id,
htmlLink: inviteLink,
inviteLink,
message: `Meeting "${title}" scheduled for ${startTime.toLocaleString()}${visitorEmail ? `. Invite sent to ${visitorEmail}.` : '.'}${inviteLink ? ` Calendar invite: ${inviteLink}` : ''}`,
addToCalendarLink,
message: `Meeting "${title}" scheduled for ${startTime.toLocaleString()}.${attendeeEmail ? ` Visitor email noted: ${attendeeEmail}.` : ''} The add-to-calendar link invites ${env.GREGOR_MEETING_EMAIL}.`,
}
} catch (error) {
console.error('Failed to schedule meeting:', error)

View File

@@ -36,7 +36,9 @@ Runtime context:
- Current server time: ${new Date().toISOString()}.
- 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.
- 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.`
const model = await servTrpc.chat.getModel()
@@ -57,7 +59,7 @@ Runtime context:
system: systemPrompt,
messages: await convertToModelMessages(messages),
tools: createChatTools(),
stopWhen: stepCountIs(2),
stopWhen: stepCountIs(3),
onFinish: async ({ text, finishReason }) => {
console.log('[ai:chat:onFinish]', {
finishReason,

View File

@@ -32,7 +32,7 @@ export default async function BlogPostPage({ params }: Props) {
const date = typeof parsed.data.date === "string" ? parsed.data.date : post.date;
return (
<main className="mx-auto h-full max-w-2xl overflow-y-auto px-4 py-12">
<main className="mx-auto max-w-2xl px-4 py-12">
<header className="mb-8">
<h1 className="text-3xl font-bold">{title}</h1>
{date && (

View File

@@ -6,7 +6,7 @@ export default async function BlogPage() {
const posts = await servTrpc.blog.list();
return (
<main className="mx-auto h-full max-w-2xl overflow-y-auto px-4 py-12">
<main className="mx-auto max-w-2xl px-4 py-12">
<h1 className="mb-8 text-3xl font-bold">Blog</h1>
{posts.length === 0 ? (
<p className="text-muted-foreground">No posts yet.</p>

View File

@@ -11,6 +11,8 @@ function toolLabel(type: string) {
return "Loading project details";
case "tool-getAvailability":
return "Checking availability";
case "tool-cancelMeeting":
return "Removing meeting";
case "tool-getCurrentUnixTime":
return "Checking current time";
default:
@@ -27,7 +29,7 @@ export const AssistantMessage = (props: { message: UIMessage }) => {
>
<div
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) => {
if (part.type === 'text') {
@@ -35,12 +37,12 @@ export const AssistantMessage = (props: { message: UIMessage }) => {
<ClientMdx key={i} source={part.text} fallback={part.text} />
)
}
if (part.type === 'tool-scheduleMeeting') {
if (part.type === 'tool-scheduleMeeting') {
const toolPart = part as unknown as {
type: 'tool-scheduleMeeting'
state: string
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') {
return (
@@ -48,33 +50,39 @@ export const AssistantMessage = (props: { message: UIMessage }) => {
Scheduling meeting
</p>
)
}
}
if (toolPart.state === 'output-available' && toolPart.output) {
const result = toolPart.output
const inviteLink = result.inviteLink ?? result.htmlLink
if (result.success) return null
return (
<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>
)
}
}
if (part.type.startsWith('tool-')) {
const toolPart = part as unknown as {
type: string

View File

@@ -14,7 +14,7 @@ export const UserMessage = (props:{message: UIMessage}) => {
>
<div
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}
</div>

View File

@@ -100,12 +100,19 @@ function PullQuote({ children }: { children: ReactNode }) {
}
function ExternalLink(props: ComponentPropsWithoutRef<"a">) {
const href = props.href ?? "";
const isExternal = /^https?:\/\//.test(href);
const { className, ...rest } = props;
if (!isExternal) return <a {...props} />;
return <a {...props} target="_blank" rel="noreferrer" />;
return (
<a
{...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]);

View File

@@ -31,6 +31,10 @@ export const env = createEnv({
CLERK_SECRET_KEY: z.string(),
ADMIN_USER_CLERK_ID: 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
.enum(["development", "test", "production"])
.default("development"),
@@ -72,6 +76,10 @@ export const env = createEnv({
POSTGRES_PRISMA_URL: process.env.POSTGRES_PRISMA_URL,
ADMIN_USER_CLERK_ID: process.env.ADMIN_USER_CLERK_ID,
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,
CLERK_SECRET_KEY: process.env.CLERK_SECRET_KEY,
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY,

View File

@@ -1,14 +1,13 @@
import "server-only";
import { clerkClient } from "@clerk/nextjs/server";
import { tool } from "ai";
import { desc } from "drizzle-orm";
import { google } from "googleapis";
import { z } from "zod";
import { cancelMeeting } from "~/app/actions/cancelMeeting";
import { scheduleMeeting } from "~/app/actions/scheduleMeeting";
import { env } from "~/env";
import { db } from "~/server/db";
import { blogPost, music } from "~/server/dbschema/schema";
import { getGoogleCalendarClient, getGoogleCalendarId } from "~/server/googleCalendar";
const contentTypeSchema = z.enum(["cv", "project", "blog", "music"]);
@@ -25,9 +24,6 @@ type SearchResult = {
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) {
return (value ?? "")
.replace(/```[\s\S]*?```/g, " ")
@@ -364,83 +360,6 @@ function logAvailability(requestId: string, message: string, data?: Record<strin
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() {
return {
scheduleMeeting: tool({
@@ -474,6 +393,13 @@ export function createChatTools() {
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({
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({
@@ -589,27 +515,24 @@ export function createChatTools() {
rangeEnd: rangeEnd.toISOString(),
});
const adminCalendar = await getAdminCalendar(requestId);
if (!adminCalendar.success) {
logAvailability(requestId, "admin calendar unavailable", {
error: adminCalendar.error,
});
return adminCalendar;
}
const calendar = getGoogleCalendarClient();
const calendarId = getGoogleCalendarId();
logAvailability(requestId, "service account calendar ready", {
calendarId,
});
let busy: Array<{ start: Date; end: Date }>;
try {
logAvailability(requestId, "freebusy request");
const response = await adminCalendar.calendar.freebusy.query({
const response = await calendar.freebusy.query({
requestBody: {
timeMin: rangeStart.toISOString(),
timeMax: rangeEnd.toISOString(),
timeZone,
items: [{ id: "primary" }],
items: [{ id: calendarId }],
},
});
busy = (response.data.calendars?.["primary"]?.busy ?? [])
busy = (response.data.calendars?.[calendarId]?.busy ?? [])
.map((item) => ({
start: parseDate(item.start ?? 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;
}