Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions apps/desktop/src/components/editor-area/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { AnnotationBox } from "./annotation-box";
import { FloatingButton } from "./floating-button";
import { NoteHeader } from "./note-header";
import { TextSelectionPopover } from "./text-selection-popover";
import { prepareContextText } from "./utils/summary-prepare";

async function generateTitleDirect(
enhancedContent: string,
Expand Down Expand Up @@ -447,6 +448,25 @@ export function useEnhanceMutation({
: config.general?.selected_template_id;

const selectedTemplate = await TemplateService.getTemplate(effectiveTemplateId ?? "");
let contextText = "";

// Print context tags if they exist
if (selectedTemplate?.context_option) {
try {
const contextConfig = JSON.parse(selectedTemplate.context_option);
if (contextConfig.type === "tags" && contextConfig.selections?.length > 0) {
// Prepare and print context text from tagged sessions
contextText = await prepareContextText(
contextConfig.selections,
sessionId,
userId,
);
}
} catch (e) {
// Silent catch for malformed JSON
console.error("Error parsing context option:", e);
}
}

if (selectedTemplate !== null) {
const eventName = selectedTemplate?.tags.includes("builtin")
Expand Down Expand Up @@ -484,6 +504,7 @@ export function useEnhanceMutation({
editor: finalInput,
words: JSON.stringify(words),
participants,
...((contextText !== "" || contextText !== undefined || contextText !== null) ? { contextText } : {}),
},
);

Expand Down
76 changes: 76 additions & 0 deletions apps/desktop/src/components/editor-area/utils/summary-prepare.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { commands as dbCommands } from "@hypr/plugin-db";

/**
* Prepares context text by finding recent enhanced notes for given tags
* @param tags Array of tag names to search for
* @param currentSessionId Session ID to exclude from results
* @param userId User ID for querying sessions
* @returns Combined context text from enhanced meeting notes
*/
export async function prepareContextText(
tags: string[],
currentSessionId: string,
userId: string,
): Promise<string> {
if (!tags.length) {
return "";
}

const allTags = await dbCommands.listAllTags();
const tagMap = new Map(allTags.map(tag => [tag.name, tag.id]));

const tagIds = tags
.map(tagName => tagMap.get(tagName))
.filter((id): id is string => id !== undefined);

if (!tagIds.length) {
return "";
}

const allSessions = new Map();

for (const tagId of tagIds) {
try {
const sessions = await dbCommands.listSessions({
type: "tagFilter",
tag_ids: [tagId],
user_id: userId,
limit: 10,
});

sessions.forEach(session => {
if (
session.id !== currentSessionId
&& session.enhanced_memo_html
&& session.enhanced_memo_html.trim().length > 0
) {
allSessions.set(session.id, session);
}
});
} catch (error) {
console.warn(`Failed to fetch sessions for tag ${tagId}:`, error);
}
}

const sortedSessions = Array.from(allSessions.values())
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
.slice(0, 2);

if (!sortedSessions.length) {
return "";
}

const contextParts = sortedSessions.map((session, index) => {
const cleanContent = session.enhanced_memo_html!
.replace(/<[^>]*>/g, "")
.replace(/&nbsp;/g, " ")
.replace(/&amp;/g, "&")
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.trim();

return `--- Session ${index + 1}: "${session.title || "Untitled Note"}" ---\n${cleanContent}`;
});

return contextParts.join("\n\n");
}
186 changes: 185 additions & 1 deletion apps/desktop/src/components/settings/views/template.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import { TemplateService } from "@/utils/template-service";
import { type Template } from "@hypr/plugin-db";
import { commands as dbCommands, type Template } from "@hypr/plugin-db";
import { Badge } from "@hypr/ui/components/ui/badge";
import { Button } from "@hypr/ui/components/ui/button";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem } from "@hypr/ui/components/ui/command";
import { Input } from "@hypr/ui/components/ui/input";
import { Popover, PopoverContent, PopoverTrigger } from "@hypr/ui/components/ui/popover";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@hypr/ui/components/ui/select";
import { Textarea } from "@hypr/ui/components/ui/textarea";
import { Trans, useLingui } from "@lingui/react/macro";
import { useQuery } from "@tanstack/react-query";
import { Plus, X } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { SectionsList } from "../components/template-sections";

Expand Down Expand Up @@ -70,6 +75,12 @@ export default function TemplateEditor({
}: TemplateEditorProps) {
const { t } = useLingui();

// Load all tags from database
const { data: allTags = [] } = useQuery({
queryKey: ["all-tags"],
queryFn: () => dbCommands.listAllTags(),
});

// Check if this is a built-in template
const isBuiltinTemplate = !TemplateService.canEditTemplate(template.id);
const isReadOnly = disabled || isBuiltinTemplate;
Expand All @@ -94,11 +105,44 @@ export default function TemplateEditor({
const [selectedEmoji, setSelectedEmoji] = useState(() => extractEmojiFromTitle(template.title || ""));
const [emojiPopoverOpen, setEmojiPopoverOpen] = useState(false);

// Context selection state
const [contextType, setContextType] = useState<string>("");
const [selectedTags, setSelectedTags] = useState<string[]>([]);

// Parse context_option from template
const parseContextOption = (contextOption: string | null) => {
if (!contextOption) {
return { type: "", selections: [] };
}
try {
const parsed = JSON.parse(contextOption);
return {
type: parsed.type || "",
selections: parsed.selections || [],
};
} catch {
return { type: "", selections: [] };
}
};

// Stringify context config for saving
const stringifyContextOption = (type: string, selections: string[]) => {
if (!type) {
return null;
}
return JSON.stringify({ type, selections });
};

// Sync local state when template ID changes (new template loaded)
useEffect(() => {
setTitleText(getTitleWithoutEmoji(template.title || ""));
setDescriptionText(template.description || "");
setSelectedEmoji(extractEmojiFromTitle(template.title || ""));

// Parse and set context option
const contextConfig = parseContextOption(template.context_option);
setContextType(contextConfig.type);
setSelectedTags(contextConfig.selections);
}, [template.id]);

// Simple handlers with local state
Expand Down Expand Up @@ -227,6 +271,146 @@ export default function TemplateEditor({
/>
</div>

{/* Context section - only show for custom templates */}
{!isBuiltinTemplate && (
<div className="flex flex-col gap-3">
<h2 className="text-sm font-medium">
<Trans>Context</Trans>
</h2>

<div className="flex flex-col gap-2">
<div className="flex flex-col gap-1">
<label className="text-xs text-neutral-600">
<Trans>Refer to past notes with:</Trans>
</label>
<Select
disabled={isReadOnly}
value={contextType}
onValueChange={(value) => {
let newContextType = "";
let newSelectedTags = selectedTags;

if (value === "none") {
newContextType = "";
newSelectedTags = [];
} else {
newContextType = value;
}

setContextType(newContextType);
setSelectedTags(newSelectedTags);

const contextOption = stringifyContextOption(newContextType, newSelectedTags);
onTemplateUpdate({ ...template, context_option: contextOption });
}}
>
<SelectTrigger className="w-full">
<SelectValue placeholder={t`Select what to use as context...`} />
</SelectTrigger>
<SelectContent>
<SelectItem value="none">
<Trans>None (disabled)</Trans>
</SelectItem>
<SelectItem value="tags">
<Trans>Tags</Trans>
</SelectItem>
</SelectContent>
</Select>
</div>

{/* Multi-select for tags */}
{contextType === "tags" && (
<div className="flex flex-col gap-1">
<label className="text-xs text-neutral-600">
<Trans>Select tags</Trans>
</label>
<div className="flex items-center gap-2">
<div className="flex-1 flex flex-wrap gap-2 min-h-[38px] p-2 border rounded-md">
{selectedTags.map((tag) => (
<Badge
key={tag}
variant="secondary"
className="flex items-center gap-1 px-2 py-0.5 text-xs bg-muted"
>
{tag}
{!isReadOnly && (
<Button
type="button"
variant="ghost"
size="sm"
className="h-3 w-3 p-0 hover:bg-transparent ml-0.5"
onClick={() => {
const newSelectedTags = selectedTags.filter((t) => t !== tag);
setSelectedTags(newSelectedTags);

// Save to template immediately
const contextOption = stringifyContextOption(contextType, newSelectedTags);
onTemplateUpdate({ ...template, context_option: contextOption });
}}
>
<X className="h-2.5 w-2.5" />
</Button>
)}
</Badge>
))}
{selectedTags.length === 0 && (
<span className="text-sm text-muted-foreground py-1">
<Trans>No tags selected</Trans>
</span>
)}
</div>
{!isReadOnly && (
<Popover>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
size="icon"
className="h-[38px] w-[38px]"
>
<Plus className="h-4 w-4" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[220px] p-0" align="end">
<Command>
<CommandInput placeholder="Search tags..." className="h-9" />
<CommandEmpty>
{allTags.length === 0
? "No tags available. Create tags by tagging your notes first."
: "No tag found."}
</CommandEmpty>
<CommandGroup className="max-h-[200px] overflow-auto">
{allTags.filter(
(tag) => !selectedTags.includes(tag.name),
).map((tag) => (
<CommandItem
key={tag.id}
onSelect={() => {
if (!selectedTags.includes(tag.name)) {
const newSelectedTags = [...selectedTags, tag.name];
setSelectedTags(newSelectedTags);

// Save to template immediately
const contextOption = stringifyContextOption(contextType, newSelectedTags);
onTemplateUpdate({ ...template, context_option: contextOption });
}
}}
>
{tag.name}
</CommandItem>
))}
</CommandGroup>
</Command>
</PopoverContent>
</Popover>
)}
</div>
</div>
)}
</div>
</div>
)}

<div className="flex flex-col gap-1">
<h2 className="text-sm font-medium">
<Trans>Sections</Trans>
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/src/components/settings/views/templates.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ export default function TemplatesView() {
description: "",
sections: [],
tags: [],
context_option: null,
};
setSelectedTemplate(newTemplate);
setViewState("new");
Expand Down
Loading
Loading