mirror of
https://github.com/MODSetter/SurfSense.git
synced 2026-06-02 19:55:18 +02:00
Implement update notion page tool
This commit is contained in:
parent
d33c0dd32f
commit
0d1b61d7e6
7 changed files with 254 additions and 329 deletions
|
|
@ -1,3 +1,4 @@
|
|||
import logging
|
||||
from typing import Any
|
||||
|
||||
from langchain_core.tools import tool
|
||||
|
|
@ -7,6 +8,8 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||
from app.connectors.notion_history import NotionHistoryConnector
|
||||
from app.services.notion import NotionToolMetadataService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def create_update_notion_page_tool(
|
||||
db_session: AsyncSession | None = None,
|
||||
|
|
@ -29,20 +32,20 @@ def create_update_notion_page_tool(
|
|||
|
||||
@tool
|
||||
async def update_notion_page(
|
||||
page_id: str,
|
||||
title: str | None = None,
|
||||
content: str | None = None,
|
||||
page_title: str,
|
||||
new_title: str | None = None,
|
||||
new_content: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Update an existing Notion page's title and/or content.
|
||||
|
||||
Use this tool when the user asks you to modify, edit, or update
|
||||
a Notion page. At least one of title or content must be provided.
|
||||
a Notion page. At least one of new_title or new_content must be provided.
|
||||
|
||||
Args:
|
||||
page_id: The ID of the Notion page to update (required).
|
||||
title: New title for the page (optional).
|
||||
content: New markdown content for the page body (optional).
|
||||
If provided, replaces all existing content.
|
||||
page_title: The current title of the Notion page to update (required).
|
||||
new_title: New title for the page (optional).
|
||||
new_content: New markdown content for the page body (optional).
|
||||
If provided, replaces all existing content.
|
||||
|
||||
Returns:
|
||||
Dictionary with:
|
||||
|
|
@ -57,49 +60,61 @@ def create_update_notion_page_tool(
|
|||
and move on. Do NOT ask for alternatives or troubleshoot.
|
||||
|
||||
Examples:
|
||||
- "Update the Notion page abc123 with title 'Updated Meeting Notes'"
|
||||
- "Change the content of page xyz789 to 'New content here'"
|
||||
- "Update page abc123 with new title 'Final Report' and content '# Summary...'"
|
||||
- "Update the 'Meeting Notes' page with new title 'Updated Meeting Notes'"
|
||||
- "Change the content of 'Project Plan' page to 'New content here'"
|
||||
- "Update 'Weekly Report' with new title 'Final Report' and content '# Summary...'"
|
||||
"""
|
||||
logger.info(f"update_notion_page called: page_title='{page_title}', new_title={new_title}, has_content={new_content is not None}")
|
||||
|
||||
if db_session is None or search_space_id is None or user_id is None:
|
||||
logger.error("Notion tool not properly configured - missing required parameters")
|
||||
return {
|
||||
"status": "error",
|
||||
"message": "Notion tool not properly configured. Please contact support.",
|
||||
}
|
||||
|
||||
if not title and not content:
|
||||
if not new_title and not new_content:
|
||||
return {
|
||||
"status": "error",
|
||||
"message": "At least one of 'title' or 'content' must be provided to update the page.",
|
||||
"message": "At least one of 'new_title' or 'new_content' must be provided to update the page.",
|
||||
}
|
||||
|
||||
try:
|
||||
metadata_service = NotionToolMetadataService(db_session)
|
||||
context = await metadata_service.get_update_context(
|
||||
search_space_id, user_id, page_id
|
||||
search_space_id, user_id, page_title
|
||||
)
|
||||
|
||||
if "error" in context:
|
||||
logger.error(f"Failed to fetch update context: {context['error']}")
|
||||
return {
|
||||
"status": "error",
|
||||
"message": context["error"],
|
||||
}
|
||||
|
||||
approval = interrupt({
|
||||
"type": "notion_page_update",
|
||||
"action": {
|
||||
"tool": "update_notion_page",
|
||||
"params": {
|
||||
"page_id": page_id,
|
||||
"title": title,
|
||||
"content": content,
|
||||
page_id = context.get("page_id")
|
||||
connector_id_from_context = context.get("account", {}).get("id")
|
||||
|
||||
logger.info(f"Requesting approval for updating Notion page: '{page_title}' (page_id={page_id})")
|
||||
approval = interrupt(
|
||||
{
|
||||
"type": "notion_page_update",
|
||||
"action": {
|
||||
"tool": "update_notion_page",
|
||||
"params": {
|
||||
"page_id": page_id,
|
||||
"title": new_title,
|
||||
"content": new_content,
|
||||
"connector_id": connector_id_from_context,
|
||||
},
|
||||
},
|
||||
},
|
||||
"context": context,
|
||||
})
|
||||
"context": context,
|
||||
}
|
||||
)
|
||||
|
||||
decisions = approval.get("decisions", [])
|
||||
if not decisions:
|
||||
logger.warning("No approval decision received")
|
||||
return {
|
||||
"status": "error",
|
||||
"message": "No approval decision received",
|
||||
|
|
@ -107,8 +122,10 @@ def create_update_notion_page_tool(
|
|||
|
||||
decision = decisions[0]
|
||||
decision_type = decision.get("type") or decision.get("decision_type")
|
||||
logger.info(f"User decision: {decision_type}")
|
||||
|
||||
if decision_type == "reject":
|
||||
logger.info("Notion page update rejected by user")
|
||||
return {
|
||||
"status": "rejected",
|
||||
"message": "User declined. The page was not updated. Do not ask again or suggest alternatives.",
|
||||
|
|
@ -118,25 +135,28 @@ def create_update_notion_page_tool(
|
|||
final_params = edited_action.get("args", {}) if edited_action else {}
|
||||
|
||||
final_page_id = final_params.get("page_id", page_id)
|
||||
final_title = final_params.get("title", title)
|
||||
final_content = final_params.get("content", content)
|
||||
final_title = final_params.get("title", new_title)
|
||||
final_content = final_params.get("content", new_content)
|
||||
final_connector_id = final_params.get("connector_id", connector_id_from_context)
|
||||
|
||||
if final_title and (not final_title or not final_title.strip()):
|
||||
# Validate title if it's being updated
|
||||
if final_title is not None and not final_title.strip():
|
||||
logger.error("Title is empty or contains only whitespace")
|
||||
return {
|
||||
"status": "error",
|
||||
"message": "Page title cannot be empty. Please provide a valid title.",
|
||||
}
|
||||
|
||||
logger.info(f"Updating Notion page with final params: page_id={final_page_id}, title={final_title}, has_content={final_content is not None}")
|
||||
|
||||
from sqlalchemy.future import select
|
||||
|
||||
from app.db import SearchSourceConnector, SearchSourceConnectorType
|
||||
|
||||
connector_id_from_context = context.get("account", {}).get("id")
|
||||
|
||||
if connector_id_from_context:
|
||||
if final_connector_id:
|
||||
result = await db_session.execute(
|
||||
select(SearchSourceConnector).filter(
|
||||
SearchSourceConnector.id == connector_id_from_context,
|
||||
SearchSourceConnector.id == final_connector_id,
|
||||
SearchSourceConnector.search_space_id == search_space_id,
|
||||
SearchSourceConnector.user_id == user_id,
|
||||
SearchSourceConnector.connector_type
|
||||
|
|
@ -146,12 +166,17 @@ def create_update_notion_page_tool(
|
|||
connector = result.scalars().first()
|
||||
|
||||
if not connector:
|
||||
logger.error(
|
||||
f"Invalid connector_id={final_connector_id} for search_space_id={search_space_id}"
|
||||
)
|
||||
return {
|
||||
"status": "error",
|
||||
"message": "Selected Notion account is invalid or has been disconnected. Please select a valid account.",
|
||||
}
|
||||
actual_connector_id = connector.id
|
||||
logger.info(f"Validated Notion connector: id={actual_connector_id}")
|
||||
else:
|
||||
logger.error("No connector found for this page")
|
||||
return {
|
||||
"status": "error",
|
||||
"message": "No connector found for this page.",
|
||||
|
|
@ -167,6 +192,7 @@ def create_update_notion_page_tool(
|
|||
title=final_title,
|
||||
content=final_content,
|
||||
)
|
||||
logger.info(f"update_page result: {result.get('status')} - {result.get('message', '')}")
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
|
|
@ -175,9 +201,12 @@ def create_update_notion_page_tool(
|
|||
if isinstance(e, GraphInterrupt):
|
||||
raise
|
||||
|
||||
logger.error(f"Error updating Notion page: {e}", exc_info=True)
|
||||
return {
|
||||
"status": "error",
|
||||
"message": str(e) if isinstance(e, ValueError) else f"Unexpected error: {e!s}",
|
||||
"message": str(e)
|
||||
if isinstance(e, ValueError)
|
||||
else f"Unexpected error: {e!s}",
|
||||
}
|
||||
|
||||
return update_notion_page
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
from dataclasses import dataclass
|
||||
|
||||
from sqlalchemy import String, and_, cast
|
||||
from sqlalchemy import and_, func
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.future import select
|
||||
|
||||
|
|
@ -79,7 +79,9 @@ class NotionToolMetadataService:
|
|||
"error": "No Notion accounts connected",
|
||||
}
|
||||
|
||||
parent_pages = await self._get_parent_pages_by_account(search_space_id, accounts)
|
||||
parent_pages = await self._get_parent_pages_by_account(
|
||||
search_space_id, accounts
|
||||
)
|
||||
|
||||
return {
|
||||
"accounts": [acc.to_dict() for acc in accounts],
|
||||
|
|
@ -87,16 +89,18 @@ class NotionToolMetadataService:
|
|||
}
|
||||
|
||||
async def get_update_context(
|
||||
self, search_space_id: int, user_id: str, page_id: str
|
||||
self, search_space_id: int, user_id: str, page_title: str
|
||||
) -> dict:
|
||||
result = await self._db_session.execute(
|
||||
select(Document)
|
||||
.join(SearchSourceConnector, Document.connector_id == SearchSourceConnector.id)
|
||||
.join(
|
||||
SearchSourceConnector, Document.connector_id == SearchSourceConnector.id
|
||||
)
|
||||
.filter(
|
||||
and_(
|
||||
Document.search_space_id == search_space_id,
|
||||
Document.document_type == DocumentType.NOTION_CONNECTOR,
|
||||
cast(Document.document_metadata["page_id"], String) == page_id,
|
||||
func.lower(Document.title) == func.lower(page_title),
|
||||
SearchSourceConnector.user_id == user_id,
|
||||
)
|
||||
)
|
||||
|
|
@ -104,7 +108,11 @@ class NotionToolMetadataService:
|
|||
document = result.scalars().first()
|
||||
|
||||
if not document:
|
||||
return {"error": f"Page {page_id} not found in your indexed documents"}
|
||||
return {
|
||||
"error": f"Page '{page_title}' not found in your indexed Notion pages. "
|
||||
"This could mean: (1) the page doesn't exist, (2) it hasn't been indexed yet, "
|
||||
"or (3) the page title is different. Please check the exact page title in Notion."
|
||||
}
|
||||
|
||||
if not document.connector_id:
|
||||
return {"error": "Document has no associated connector"}
|
||||
|
|
@ -124,6 +132,10 @@ class NotionToolMetadataService:
|
|||
|
||||
account = NotionAccount.from_connector(connector)
|
||||
|
||||
page_id = document.document_metadata.get("page_id")
|
||||
if not page_id:
|
||||
return {"error": "Page ID not found in document metadata"}
|
||||
|
||||
return {
|
||||
"account": account.to_dict(),
|
||||
"page_id": page_id,
|
||||
|
|
@ -134,9 +146,9 @@ class NotionToolMetadataService:
|
|||
}
|
||||
|
||||
async def get_delete_context(
|
||||
self, search_space_id: int, user_id: str, page_id: str
|
||||
self, search_space_id: int, user_id: str, page_title: str
|
||||
) -> dict:
|
||||
return await self.get_update_context(search_space_id, user_id, page_id)
|
||||
return await self.get_update_context(search_space_id, user_id, page_title)
|
||||
|
||||
async def _get_notion_accounts(
|
||||
self, search_space_id: int, user_id: str
|
||||
|
|
|
|||
|
|
@ -136,6 +136,7 @@ const TOOLS_WITH_UI = new Set([
|
|||
"delete_notion_page",
|
||||
"scrape_webpage",
|
||||
"create_notion_page",
|
||||
"update_notion_page",
|
||||
// "write_todos", // Disabled for now
|
||||
]);
|
||||
|
||||
|
|
|
|||
|
|
@ -189,7 +189,8 @@ button {
|
|||
|
||||
/* Human-in-the-loop approval card animations */
|
||||
@keyframes pulse-subtle {
|
||||
0%, 100% {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 1;
|
||||
box-shadow: 0 0 0 0 rgb(0 0 0 / 0.15);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,14 +5,13 @@ import {
|
|||
AlertTriangleIcon,
|
||||
CheckIcon,
|
||||
Loader2Icon,
|
||||
Maximize2Icon,
|
||||
MaximizeIcon,
|
||||
MinimizeIcon,
|
||||
PencilIcon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
|
||||
interface InterruptResult {
|
||||
|
|
@ -51,6 +50,8 @@ interface SuccessResult {
|
|||
page_id: string;
|
||||
title: string;
|
||||
url: string;
|
||||
content_preview?: string;
|
||||
content_length?: number;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
|
|
@ -79,109 +80,6 @@ function isErrorResult(result: unknown): result is ErrorResult {
|
|||
);
|
||||
}
|
||||
|
||||
function PageContextDisplay({
|
||||
account,
|
||||
currentTitle,
|
||||
currentContent,
|
||||
}: {
|
||||
account?: {
|
||||
id: number;
|
||||
name: string;
|
||||
workspace_id: string | null;
|
||||
workspace_name: string;
|
||||
workspace_icon: string;
|
||||
};
|
||||
currentTitle?: string;
|
||||
currentContent?: string;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
{account && (
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs font-medium text-muted-foreground">Notion Account</div>
|
||||
<div className="text-sm text-foreground p-2 bg-card rounded border border-border">
|
||||
{account.workspace_name}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{currentTitle && (
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs font-medium text-muted-foreground">Current Page Title</div>
|
||||
<div className="text-sm text-foreground p-2 bg-card rounded border border-border">
|
||||
{currentTitle}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{currentContent && (
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs font-medium text-muted-foreground">
|
||||
Current Content (first 200 chars)
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground p-2 bg-card rounded border border-border font-mono text-xs">
|
||||
{currentContent.slice(0, 200)}
|
||||
{currentContent.length > 200 && "..."}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function EditFormFields({
|
||||
editedArgs,
|
||||
setEditedArgs,
|
||||
isTitleValid,
|
||||
idPrefix = "",
|
||||
rows = 8,
|
||||
}: {
|
||||
editedArgs: Record<string, unknown>;
|
||||
setEditedArgs: (args: Record<string, unknown>) => void;
|
||||
isTitleValid: boolean;
|
||||
idPrefix?: string;
|
||||
rows?: number;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
<div>
|
||||
<label
|
||||
htmlFor={`${idPrefix}notion-title`}
|
||||
className="text-xs font-medium text-muted-foreground mb-1.5 block"
|
||||
>
|
||||
Title <span className="text-destructive">*</span>
|
||||
</label>
|
||||
<Input
|
||||
id={`${idPrefix}notion-title`}
|
||||
value={String(editedArgs.title ?? "")}
|
||||
onChange={(e) => setEditedArgs({ ...editedArgs, title: e.target.value })}
|
||||
placeholder="Enter page title"
|
||||
className={!isTitleValid ? "border-destructive" : ""}
|
||||
/>
|
||||
{!isTitleValid && (
|
||||
<p className="text-xs text-destructive mt-1">Title is required and cannot be empty</p>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<label
|
||||
htmlFor={`${idPrefix}notion-content`}
|
||||
className="text-xs font-medium text-muted-foreground mb-1.5 block"
|
||||
>
|
||||
Content (optional)
|
||||
</label>
|
||||
<Textarea
|
||||
id={`${idPrefix}notion-content`}
|
||||
value={String(editedArgs.content ?? "")}
|
||||
onChange={(e) => setEditedArgs({ ...editedArgs, content: e.target.value })}
|
||||
placeholder="Enter page content"
|
||||
rows={rows}
|
||||
className="resize-none font-mono text-xs"
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ApprovalCard({
|
||||
args,
|
||||
interruptData,
|
||||
|
|
@ -200,21 +98,14 @@ function ApprovalCard({
|
|||
);
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [isFullScreen, setIsFullScreen] = useState(false);
|
||||
const [editedArgs, setEditedArgs] = useState<Record<string, unknown>>(args);
|
||||
|
||||
const account = interruptData.context?.account;
|
||||
const currentTitle = interruptData.context?.current_title;
|
||||
const currentContent = interruptData.context?.current_content;
|
||||
|
||||
const [editedArgs, setEditedArgs] = useState<Record<string, unknown>>({
|
||||
...args,
|
||||
title: args.title || currentTitle || "",
|
||||
content: args.content || currentContent || "",
|
||||
});
|
||||
|
||||
const isTitleValid = useMemo((): boolean => {
|
||||
const title = isEditing ? editedArgs.title : args.title || currentTitle;
|
||||
return Boolean(title && typeof title === "string" && title.trim().length > 0);
|
||||
}, [isEditing, editedArgs.title, args.title, currentTitle]);
|
||||
// Title is not editable, so it's always valid
|
||||
const isTitleValid = true;
|
||||
|
||||
const reviewConfig = interruptData.review_configs[0];
|
||||
const allowedDecisions = reviewConfig?.allowed_decisions ?? ["approve", "reject"];
|
||||
|
|
@ -222,7 +113,7 @@ function ApprovalCard({
|
|||
|
||||
return (
|
||||
<div
|
||||
className={`my-4 max-w-full overflow-hidden rounded-xl transition-all duration-300 ${
|
||||
className={`my-4 ${isFullScreen ? "fixed inset-0 z-50 m-0 flex flex-col bg-background" : "max-w-full"} overflow-hidden rounded-xl transition-all duration-300 ${
|
||||
decided
|
||||
? "border border-border bg-card shadow-sm"
|
||||
: "border-2 border-foreground/20 bg-muted/30 dark:bg-muted/10 shadow-lg animate-pulse-subtle"
|
||||
|
|
@ -254,68 +145,89 @@ function ApprovalCard({
|
|||
{isEditing ? "You can edit the arguments below" : "Requires your approval to proceed"}
|
||||
</p>
|
||||
</div>
|
||||
{canEdit && !decided && !isEditing && (
|
||||
<>
|
||||
<Button size="sm" variant="ghost" onClick={() => setIsFullScreen(true)}>
|
||||
<Maximize2Icon className="size-4" />
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => setIsEditing(true)}>
|
||||
<PencilIcon className="size-4" />
|
||||
Edit
|
||||
</Button>
|
||||
</>
|
||||
{isEditing && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => setIsFullScreen(!isFullScreen)}
|
||||
className="shrink-0"
|
||||
>
|
||||
{isFullScreen ? <MinimizeIcon className="size-4" /> : <MaximizeIcon className="size-4" />}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Context section - READ ONLY account and page info */}
|
||||
{!decided && interruptData.context && (
|
||||
<div className="border-b border-border px-4 py-3 bg-muted/30 space-y-3">
|
||||
{interruptData.context.error ? (
|
||||
<p className="text-sm text-destructive">{interruptData.context.error}</p>
|
||||
) : (
|
||||
<PageContextDisplay
|
||||
account={account}
|
||||
currentTitle={currentTitle}
|
||||
currentContent={currentContent}
|
||||
/>
|
||||
<>
|
||||
{account && (
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs font-medium text-muted-foreground">Notion Account</div>
|
||||
<div className="w-full rounded-md border border-input bg-muted/50 px-3 py-2 text-sm">
|
||||
{account.workspace_icon} {account.workspace_name}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{currentTitle && (
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs font-medium text-muted-foreground">Current Page</div>
|
||||
<div className="w-full rounded-md border border-input bg-muted/50 px-3 py-2 text-sm">
|
||||
📄 {currentTitle}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Display mode - show proposed changes as read-only */}
|
||||
{!isEditing && (
|
||||
<div className="space-y-2 px-4 py-3 bg-card">
|
||||
{args.title != null && (
|
||||
<div>
|
||||
<div className="text-xs font-medium text-muted-foreground mb-1.5 block">
|
||||
New Title
|
||||
</div>
|
||||
<p className="text-sm text-foreground">{String(args.title)}</p>
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
className={`space-y-2 px-4 py-3 bg-card ${isFullScreen ? "flex-1 overflow-y-auto" : ""}`}
|
||||
>
|
||||
{args.content != null && (
|
||||
<div>
|
||||
<div className="text-xs font-medium text-muted-foreground mb-1.5 block">
|
||||
New Content
|
||||
</div>
|
||||
<p className="text-sm text-foreground whitespace-pre-wrap font-mono text-xs">
|
||||
{String(args.content).slice(0, 300)}
|
||||
{String(args.content).length > 300 && "..."}
|
||||
<p className="text-xs font-medium text-muted-foreground">New Content</p>
|
||||
<p className="line-clamp-4 text-sm whitespace-pre-wrap text-foreground">
|
||||
{String(args.content)}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{args.content == null && (
|
||||
<p className="text-sm text-muted-foreground italic">No content update specified</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Edit mode - show editable form fields */}
|
||||
{isEditing && !decided && (
|
||||
<div className="space-y-3 px-4 py-3 bg-card">
|
||||
<EditFormFields
|
||||
editedArgs={editedArgs}
|
||||
setEditedArgs={setEditedArgs}
|
||||
isTitleValid={isTitleValid}
|
||||
rows={8}
|
||||
<div
|
||||
className={`px-4 py-3 bg-card ${isFullScreen ? "flex-1 flex flex-col overflow-hidden" : ""}`}
|
||||
>
|
||||
<label
|
||||
htmlFor="notion-content"
|
||||
className="text-xs font-medium text-muted-foreground mb-1.5 block"
|
||||
>
|
||||
New Content
|
||||
</label>
|
||||
<Textarea
|
||||
id="notion-content"
|
||||
value={String(editedArgs.content ?? "")}
|
||||
onChange={(e) => setEditedArgs({ ...editedArgs, content: e.target.value || null })}
|
||||
placeholder={currentContent || "Enter new content"}
|
||||
rows={isFullScreen ? undefined : 12}
|
||||
className={`resize-none ${isFullScreen ? "flex-1 min-h-0" : ""}`}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Action buttons */}
|
||||
<div
|
||||
className={`flex items-center gap-2 border-t ${
|
||||
decided ? "border-border bg-card" : "border-foreground/15 bg-muted/20 dark:bg-muted/10"
|
||||
|
|
@ -342,15 +254,19 @@ function ApprovalCard({
|
|||
onClick={() => {
|
||||
setDecided("edit");
|
||||
setIsEditing(false);
|
||||
setIsFullScreen(false);
|
||||
onDecision({
|
||||
type: "edit",
|
||||
edited_action: {
|
||||
name: interruptData.action_requests[0].name,
|
||||
args: editedArgs,
|
||||
args: {
|
||||
page_id: args.page_id,
|
||||
content: editedArgs.content,
|
||||
connector_id: account?.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
}}
|
||||
disabled={!isTitleValid}
|
||||
>
|
||||
<CheckIcon />
|
||||
Approve with Changes
|
||||
|
|
@ -360,11 +276,8 @@ function ApprovalCard({
|
|||
variant="outline"
|
||||
onClick={() => {
|
||||
setIsEditing(false);
|
||||
setEditedArgs({
|
||||
...args,
|
||||
title: args.title || currentTitle || "",
|
||||
content: args.content || currentContent || "",
|
||||
});
|
||||
setIsFullScreen(false);
|
||||
setEditedArgs(args); // Reset to original args
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
|
|
@ -381,23 +294,32 @@ function ApprovalCard({
|
|||
type: "approve",
|
||||
edited_action: {
|
||||
name: interruptData.action_requests[0].name,
|
||||
args: args,
|
||||
args: {
|
||||
page_id: args.page_id,
|
||||
content: args.content,
|
||||
connector_id: account?.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
}}
|
||||
disabled={!isTitleValid}
|
||||
>
|
||||
<CheckIcon />
|
||||
Approve
|
||||
</Button>
|
||||
)}
|
||||
{canEdit && (
|
||||
<Button size="sm" variant="outline" onClick={() => setIsEditing(true)}>
|
||||
<PencilIcon />
|
||||
Edit
|
||||
</Button>
|
||||
)}
|
||||
{allowedDecisions.includes("reject") && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="destructive"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setDecided("reject");
|
||||
onDecision({ type: "reject" });
|
||||
onDecision({ type: "reject", message: "User rejected the action." });
|
||||
}}
|
||||
>
|
||||
<XIcon />
|
||||
|
|
@ -407,114 +329,77 @@ function ApprovalCard({
|
|||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Dialog open={isFullScreen} onOpenChange={setIsFullScreen}>
|
||||
<DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Update Notion Page</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<PageContextDisplay
|
||||
account={account}
|
||||
currentTitle={currentTitle}
|
||||
currentContent={undefined}
|
||||
/>
|
||||
|
||||
<div className="space-y-4">
|
||||
<EditFormFields
|
||||
editedArgs={editedArgs}
|
||||
setEditedArgs={setEditedArgs}
|
||||
isTitleValid={isTitleValid}
|
||||
idPrefix="fullscreen-"
|
||||
rows={20}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 justify-end pt-4 border-t">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setDecided("edit");
|
||||
setIsFullScreen(false);
|
||||
onDecision({
|
||||
type: "edit",
|
||||
edited_action: {
|
||||
name: interruptData.action_requests[0].name,
|
||||
args: editedArgs,
|
||||
},
|
||||
});
|
||||
}}
|
||||
disabled={!isTitleValid}
|
||||
>
|
||||
<CheckIcon />
|
||||
Approve with Changes
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setIsFullScreen(false);
|
||||
setEditedArgs({
|
||||
...args,
|
||||
title: args.title || currentTitle || "",
|
||||
content: args.content || currentContent || "",
|
||||
});
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LoadingCard() {
|
||||
return (
|
||||
<div className="my-4 flex items-center gap-3 rounded-xl border-2 border-blue-200 bg-blue-50 px-4 py-3 dark:border-blue-900 dark:bg-blue-950">
|
||||
<Loader2Icon className="size-5 animate-spin text-blue-600 dark:text-blue-400" />
|
||||
<p className="text-sm text-blue-900 dark:text-blue-100">Updating Notion page...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SuccessCard({ result }: { result: SuccessResult }) {
|
||||
return (
|
||||
<div className="my-4 rounded-xl border border-green-200 bg-green-50 p-4 dark:border-green-900 dark:bg-green-950">
|
||||
<div className="flex items-start gap-3">
|
||||
<CheckIcon className="size-5 shrink-0 text-green-600 dark:text-green-400" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<p className="text-sm font-medium text-green-900 dark:text-green-100">
|
||||
Updated Notion page '{result.title}'
|
||||
</p>
|
||||
{result.url && (
|
||||
<a
|
||||
href={result.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-block text-sm text-green-700 underline hover:text-green-800 dark:text-green-300 dark:hover:text-green-200"
|
||||
>
|
||||
Open in Notion →
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ErrorCard({ result }: { result: ErrorResult }) {
|
||||
return (
|
||||
<div className="my-4 rounded-xl border border-red-200 bg-red-50 p-4 dark:border-red-900 dark:bg-red-950">
|
||||
<div className="flex items-start gap-3">
|
||||
<XIcon className="size-5 shrink-0 text-red-600 dark:text-red-400" />
|
||||
<div className="flex-1">
|
||||
<p className="text-sm font-medium text-red-900 dark:text-red-100">
|
||||
Failed to update page
|
||||
</p>
|
||||
<p className="mt-1 text-sm text-red-700 dark:text-red-300">{result.message}</p>
|
||||
<div className="my-4 max-w-md overflow-hidden rounded-xl border border-destructive/50 bg-card">
|
||||
<div className="flex items-center gap-3 border-b border-destructive/50 px-4 py-3">
|
||||
<div className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-destructive/10">
|
||||
<XIcon className="size-4 text-destructive" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium text-destructive">Failed to update Notion page</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="px-4 py-3">
|
||||
<p className="text-sm text-muted-foreground">{result.message}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SuccessCard({ result }: { result: SuccessResult }) {
|
||||
return (
|
||||
<div className="my-4 max-w-md overflow-hidden rounded-xl border border-border bg-card">
|
||||
<div className="flex items-center gap-3 border-b border-border px-4 py-3">
|
||||
<div className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-green-500/10">
|
||||
<CheckIcon className="size-4 text-green-500" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-[.8rem] text-muted-foreground">
|
||||
{result.message || "Notion page updated successfully"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Show details to verify the update */}
|
||||
<div className="space-y-2 px-4 py-3 text-xs">
|
||||
<div>
|
||||
<span className="font-medium text-muted-foreground">Page ID: </span>
|
||||
<span className="font-mono">{result.page_id}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="font-medium text-muted-foreground">Title: </span>
|
||||
<span>{result.title}</span>
|
||||
</div>
|
||||
{result.url && (
|
||||
<div>
|
||||
<span className="font-medium text-muted-foreground">URL: </span>
|
||||
<a
|
||||
href={result.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary hover:underline"
|
||||
>
|
||||
Open in Notion
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
{result.content_length != null && (
|
||||
<div>
|
||||
<span className="font-medium text-muted-foreground">Content: </span>
|
||||
<span>{result.content_length} characters</span>
|
||||
</div>
|
||||
)}
|
||||
{result.content_preview && (
|
||||
<div>
|
||||
<span className="font-medium text-muted-foreground">Preview: </span>
|
||||
<span className="text-muted-foreground italic">{result.content_preview}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
|
@ -525,14 +410,21 @@ export const UpdateNotionPageToolUI = makeAssistantToolUI<
|
|||
UpdateNotionPageResult
|
||||
>({
|
||||
toolName: "update_notion_page",
|
||||
render: function UpdateNotionPageUI({ result, addResult, status }) {
|
||||
render: function UpdateNotionPageUI({ args, result, status }) {
|
||||
if (status.type === "running") {
|
||||
return <LoadingCard />;
|
||||
return (
|
||||
<div className="my-4 flex max-w-md items-center gap-3 rounded-xl border border-border bg-card px-4 py-3">
|
||||
<Loader2Icon className="size-4 animate-spin text-muted-foreground" />
|
||||
<p className="text-sm text-muted-foreground">Updating Notion page...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!result) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isInterruptResult(result)) {
|
||||
const args = result.action_requests[0]?.args || {};
|
||||
|
||||
return (
|
||||
<ApprovalCard
|
||||
args={args}
|
||||
|
|
@ -560,13 +452,6 @@ export const UpdateNotionPageToolUI = makeAssistantToolUI<
|
|||
return <ErrorCard result={result} />;
|
||||
}
|
||||
|
||||
if (typeof result === "object" && result !== null && "status" in result) {
|
||||
const successResult = result as SuccessResult;
|
||||
if (successResult.status === "success") {
|
||||
return <SuccessCard result={successResult} />;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
return <SuccessCard result={result as SuccessResult} />;
|
||||
},
|
||||
});
|
||||
|
|
|
|||
|
|
@ -4,8 +4,8 @@ import type React from "react";
|
|||
import { createContext, useContext, useEffect, useState } from "react";
|
||||
import enMessages from "../messages/en.json";
|
||||
import esMessages from "../messages/es.json";
|
||||
import ptMessages from "../messages/pt.json";
|
||||
import hiMessages from "../messages/hi.json";
|
||||
import ptMessages from "../messages/pt.json";
|
||||
import zhMessages from "../messages/zh.json";
|
||||
|
||||
type Locale = "en" | "es" | "pt" | "hi" | "zh";
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ export interface ThinkingStepData {
|
|||
items: string[];
|
||||
}
|
||||
|
||||
|
||||
export type ContentPart =
|
||||
| { type: "text"; text: string }
|
||||
| {
|
||||
|
|
@ -18,24 +17,25 @@ export type ContentPart =
|
|||
result?: unknown;
|
||||
};
|
||||
|
||||
|
||||
export interface ContentPartsState {
|
||||
contentParts: ContentPart[];
|
||||
currentTextPartIndex: number;
|
||||
toolCallIndices: Map<string, number>;
|
||||
}
|
||||
|
||||
|
||||
export function appendText(state: ContentPartsState, delta: string): void {
|
||||
if (state.currentTextPartIndex >= 0 && state.contentParts[state.currentTextPartIndex]?.type === "text") {
|
||||
(state.contentParts[state.currentTextPartIndex] as { type: "text"; text: string }).text += delta;
|
||||
if (
|
||||
state.currentTextPartIndex >= 0 &&
|
||||
state.contentParts[state.currentTextPartIndex]?.type === "text"
|
||||
) {
|
||||
(state.contentParts[state.currentTextPartIndex] as { type: "text"; text: string }).text +=
|
||||
delta;
|
||||
} else {
|
||||
state.contentParts.push({ type: "text", text: delta });
|
||||
state.currentTextPartIndex = state.contentParts.length - 1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export function addToolCall(
|
||||
state: ContentPartsState,
|
||||
toolsWithUI: Set<string>,
|
||||
|
|
@ -55,7 +55,6 @@ export function addToolCall(
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
export function updateToolCall(
|
||||
state: ContentPartsState,
|
||||
toolCallId: string,
|
||||
|
|
@ -69,7 +68,6 @@ export function updateToolCall(
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
export function buildContentForUI(
|
||||
state: ContentPartsState,
|
||||
toolsWithUI: Set<string>
|
||||
|
|
@ -84,7 +82,6 @@ export function buildContentForUI(
|
|||
: [{ type: "text", text: "" }];
|
||||
}
|
||||
|
||||
|
||||
export function buildContentForPersistence(
|
||||
state: ContentPartsState,
|
||||
toolsWithUI: Set<string>,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue