Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adhd bot #80

Closed
wants to merge 28 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
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
8 changes: 8 additions & 0 deletions assets/src/addie.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import '@/styles/index.css'
import 'vite/modulepreload-polyfill'

import { render } from 'preact'

import Addie from '@/screens/addie/Addie'

render(<Addie />, document.getElementById('app')!)
22 changes: 20 additions & 2 deletions assets/src/api/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,17 @@ import { encode } from 'base64-arraybuffer'

import { config, OAuthProvider } from '@/config'
import {
AuthToken, AuthTokenPair, File as LNFile, FileType, OAuthToken, Period, Project, ProjectRole,
Task, Team, User
AuthToken,
AuthTokenPair,
File as LNFile,
FileType,
OAuthToken,
Period,
Project,
ProjectRole,
Task,
Team,
User,
} from '@/models'
import { AsyncPromise, logger } from '@/utils'

Expand Down Expand Up @@ -428,6 +437,15 @@ class APIService {
return response.data
}

async generateChat(
messages: { role: string; content: string }[]
): Promise<{ response: string; status: number }> {
const response = await this.axios.post(`${this.endpoint}/generate/addie`, {
messages,
})
return { response: response.data, status: response.status }
}

// misc

async githash(): Promise<{ hash: string }> {
Expand Down
1 change: 0 additions & 1 deletion assets/src/components/journal/DailyPrompt.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ const prompts = [
' “If there are nine rabbits on the ground, if you want to catch one, just focus on one.” – Jack Ma',
'“You may delay, but time will not.” – Benjamin Franklin',
'“The tragedy in life doesn’t lie in not reaching your goal. The tragedy lies in having no goal to reach.” – Benjamin E. Mays',
'“If you are interested in balancing work and pleasure, stop trying to balance them. Instead make your work more pleasurable.” – Donald Trump',
'“Both good and bad days should end with productivity. Your mood affairs should never influence your work.” – Greg Evans',
'“When one has much to put into them, a day has a hundred pockets.” – Friedrich Nietzsche',
'“Focus on being productive instead of busy.” -Tim Ferriss',
Expand Down
4 changes: 4 additions & 0 deletions assets/src/config/paths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,8 @@ export const paths = {
INSIGHT_DOC: '/insight/docs',

INSIGHT_SETTINGS: '/insight/settings',

// --- addie

ADDIE: '/addie',
}
Binary file added assets/src/images/therapist.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions assets/src/models/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export * from './daily_note'
export * from './doc'
export * from './file'
export * from './message'
export * from './oauth_token'
export * from './project'
export * from './task'
Expand Down
13 changes: 13 additions & 0 deletions assets/src/models/message.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export enum Author {
BOT,
YOU,
}

export class Message {
constructor(public from: Author, public text: string) {}
}

export type GPTMessage = {
role: 'assistant' | 'user' | 'system'
content: string
}
39 changes: 39 additions & 0 deletions assets/src/screens/addie/Addie.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { useEffect, useState } from 'preact/hooks'

import Button from '@/components/core/Button'
import Loader from '@/components/core/Loader'
import { paths } from '@/config'
import ChatMain from '@/screens/addie/ChatMain'
import { authStore } from '@/stores/authStore'
import tracker from '@/stores/tracker'
import { uiStore } from '@/stores/uiStore'
import { useStore } from '@nanostores/preact'

export default () => {
const user = useStore(authStore.loggedInUser)

useEffect(() => {
uiStore.insightLoop = true
if (user === undefined) authStore.init()
else if (user === null)
location.href = paths.SIGNUP + '?path=' + location.pathname + location.search
else {
uiStore.initLoggedInUser(user)
tracker.openAddie()
}
}, [user])

if (!user)
return (
<div class="w-10 mx-auto my-40">
<Loader class="my-40" size={80} />
<Button onClick={() => location.reload()}>Refresh</Button>
</div>
)

return (
<div class="w-full h-full min-w-[300px] bg-gray-100">
<ChatMain />
</div>
)
}
177 changes: 177 additions & 0 deletions assets/src/screens/addie/ChatMain.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
import { useEffect, useRef, useState } from 'preact/hooks'

import Input from '@/components/core/Input'
import Pressable from '@/components/core/Pressable'
import therapist from '@/images/therapist.png'
import { Author, Message } from '@/models'
import addieScript from '@/screens/addie/addieScript'
import { addieStore } from '@/stores/addieStore'
import { useStore } from '@nanostores/preact'

export default () => {
useEffect(() => {
addieStore.resetConversation()
}, [])

return (
<div class="mx-auto max-w-2xl bg-white p-4 lg:p-10 flex flex-col h-full overflow-auto">
<div class="flex mb-4 justify-between items-center">
<img src={therapist} class="w-10 h-10" />
<Pressable onClick={() => addieStore.resetConversation()} tooltip="Start Over">
Start Over
</Pressable>
</div>
<Messages />
<AwaitingResponse />
<Response />
<ErrorMessage />
</div>
)
}

function Messages() {
const divRef = useRef<HTMLDivElement>(null)
const messages = useStore(addieStore.messages)

useEffect(() => {
const div = divRef.current
if (!div) return
const lastMessage = div.children[div.children.length - 1]
if (lastMessage) lastMessage.scrollIntoView()
}, [messages])

return (
<div ref={divRef} class="flex flex-col">
{messages.map((message, i) => {
const props = { message, prevMessage: messages[i - 1], key: i }
return message.from == Author.BOT ? <BotMessage {...props} /> : <UserMessage {...props} />
})}
</div>
)
}

function AwaitingResponse() {
const awaitingResponse = useStore(addieStore.awaitingResponse)

if (!awaitingResponse) return null

return (
<div class="flex flex-col mb-4 max-w-xl">
<div class="bg-purple-300 px-4 py-2 rounded-lg">
<div class="dot-flashing ml-4 my-2" />
</div>
</div>
)
}

type MessageProps = { message: Message; prevMessage: Message | undefined }

function BotMessage({ message, prevMessage }: MessageProps) {
return (
<div class="flex flex-col mb-4 max-w-xl">
<div class="bg-purple-300 px-4 py-2 rounded-lg whitespace-pre-wrap">{message.text}</div>
</div>
)
}

function UserMessage({ message }: MessageProps) {
return (
<div class="flex flex-col mb-4 items-end">
<div class="bg-gray-200 px-4 py-2 rounded-lg">{message.text}</div>
</div>
)
}

function Response() {
const divRef = useRef<HTMLDivElement>(null)
const response = useStore(addieStore.response)

useEffect(() => {
if (divRef.current) divRef.current.scrollIntoView()
}, [response])

if (!response) return null

if (response.kind == 'end') {
return (
<div ref={divRef}>
If you have additional feedback, send it to Tim (tim@daybird.app).
<a href="#" class="text-blue-600 block" onClick={() => addieStore.resetConversation()}>
Start Over?
</a>
</div>
)
}

return (
<>
{(response.kind == 'buttons' || response.kind == 'buttons_text') && (
<>
<div ref={divRef} class="flex gap-2 justify-center flex-wrap">
{response.buttons?.map((button, i) => (
<button
class="bg-gray-300 hover:bg-gray-400 px-4 py-2 rounded-lg border border-gray-700"
onClick={() => {
addieStore.addUserMessage(button)
addieScript.handleButton(i)
}}
>
{button}
</button>
))}
</div>
</>
)}

{response.kind == 'buttons_text' && <div class="h-4 min-h-[1rem]" />}

{(response.kind == 'text' || response.kind == 'buttons_text') && (
<div ref={divRef}>
<TextResponse />
</div>
)}
</>
)
}

function TextResponse() {
const response = useStore(addieStore.response)
const [textInput, setTextInput] = useState('')

const handleSubmit = (e: Event) => {
e.preventDefault()
if (textInput.trim().length == 0) return

addieStore.addUserMessage(textInput)
addieScript.handleInput(textInput)
setTextInput('')
}

return (
<form onSubmit={handleSubmit}>
<input
ref={(ref) => ref && ref.focus()}
value={textInput}
placeholder={response?.placeholder || 'Type your response here'}
onChange={(e) => setTextInput((e.target as HTMLInputElement).value)}
className={`appearance-none block w-full px-3 py-2 border border-gray-300
rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-blue-500
focus:border-blue-500 text-sm`}
/>
</form>
)
}

function ErrorMessage() {
const error = useStore(addieStore.error)
if (!error) return null

return (
<div
class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mt-4"
role="alert"
>
<span class="block sm:inline">{error}</span>
</div>
)
}
37 changes: 37 additions & 0 deletions assets/src/screens/addie/HeadlessEditor.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { decode } from 'base64-arraybuffer'
import * as Y from 'yjs'

import { Project } from '@/models'
import { docStore } from '@/stores/docStore'
import { Editor } from '@tiptap/core'
import Collaboration from '@tiptap/extension-collaboration'
import StarterKit from '@tiptap/starter-kit'

export const loadDoc = async (project: Project, id: string, ydoc: Y.Doc) => {
await docStore.loadDoc(project, id)
const contents = docStore.doc.get()?.contents
if (contents) {
const array = new Uint8Array(decode(contents))
Y.applyUpdate(ydoc, array)
}
return ydoc
}

export const createEditor = (ydoc: Y.Doc) => {
const editor = new Editor({
extensions: [
StarterKit.configure({
// The Collaboration extension comes with its own history handling
history: false,
}),
Collaboration.configure({
document: ydoc,
}),
],
})
return editor
}

export const convertToDoc = (ydoc: Y.Doc) => {
return Y.encodeStateAsUpdate(ydoc)
}
Loading
Loading