Skip to content

Commit

Permalink
Merge pull request #25 from your-papa/dev
Browse files Browse the repository at this point in the history
Release 0.2.2
  • Loading branch information
nicobrauchtgit authored Feb 27, 2024
2 parents 8f4e7d7 + 2ef4404 commit 22a137e
Show file tree
Hide file tree
Showing 9 changed files with 81 additions and 48 deletions.
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "Interact with your privacy focused assistant, leveraging Ollama or OpenAI, making your second brain even smarter.",
"author": "Leo310, nicobrauchtgit",
"authorUrl": "https://github.com/nicobrauchtgit",
"version": "0.2.1",
"version": "0.2.2",
"minAppVersion": "1.5.0",
"isDesktopOnly": true
}
22 changes: 12 additions & 10 deletions src/components/Chat/Input.svelte
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<script lang="ts">
import { Notice, setIcon } from 'obsidian';
import type { KeyboardEventHandler } from 'svelte/elements';
import { runSecondBrainFromChat } from '../../controller/runSecondBrain';
import { runSecondBrain, canRunSecondBrain } from '../../controller/runSecondBrain';
import { nanoid } from 'nanoid';
import { plugin, chatHistory, chatInput, isEditingAssistantMessage, papaState, papaIndexingProgress, isChatInSidebar } from '../../store';
import ProgressCircle from '../base/ProgressCircle.svelte';
Expand All @@ -12,7 +12,9 @@
setIcon(node, iconId);
};
async function runSecondBrain() {
async function runSecondBrainFromInput() {
if (!canRunSecondBrain()) return;
if ($isEditingAssistantMessage) {
$chatHistory[0].content = $chatInput;
$plugin.data.initialAssistantMessage = $chatInput;
Expand All @@ -26,7 +28,7 @@
if ($chatInput.trim() !== '') {
let userQuery = $chatInput;
$chatInput = '';
await runSecondBrainFromChat($plugin.data.isUsingRag, userQuery);
await runSecondBrain($plugin.data.isUsingRag, userQuery);
}
}
function injectContext(event: KeyboardEvent): KeyboardEventHandler<HTMLInputElement> {
Expand All @@ -53,7 +55,7 @@
function handelEnter(event: KeyboardEvent) {
if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault();
runSecondBrain();
runSecondBrainFromInput();
}
}
Expand Down Expand Up @@ -126,16 +128,16 @@
class="h-8 rounded-r-md px-4 py-2 transition duration-300 ease-in-out hover:bg-[--text-accent-hover]"
use:icon={'stop-circle'}
/>
{:else if $papaState === 'indexing' || $papaState === 'loading' || $papaState === 'indexing-paused'}
<div class="flex h-8 items-center px-4 py-2">
<ProgressCircle bind:progress={$papaIndexingProgress} />
</div>
{:else}
{:else if $papaState === 'idle'}
<button
aria-label="Run your Smart Second Brain"
on:click={runSecondBrain}
on:click={runSecondBrainFromInput}
class="h-8 rounded-r-md px-4 py-2 transition duration-300 ease-in-out hover:bg-[--text-accent-hover]"
use:icon={'send-horizontal'}
/>
{:else}
<div class="flex h-8 items-center px-4 py-2">
<ProgressCircle bind:progress={$papaIndexingProgress} />
</div>
{/if}
</div>
28 changes: 18 additions & 10 deletions src/components/Chat/QuickSettingsDrawer.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
<div class={`relative ${isOpen ? 'h-[33%] min-h-[33%]' : 'h-[--icon-m] min-h-[--icon-m]'} overflow-hidden transition-all duration-300 ease-in-out`}>
<div class="flex h-full flex-col items-center justify-center">
{#if isOpen}
{#if $papaState === 'loading'}
{#if $papaState === 'loading' || $papaState === 'uninitialized'}
<h2 class="text-center text-[--text-normal]">Starting...</h2>
{:else if $papaState === 'indexing'}
<h2 class="text-center text-[--text-normal]">Indexing vault...</h2>
Expand All @@ -69,7 +69,23 @@
/>
<ProgressBar progress={$papaIndexingProgress} />
</div>
{:else if $papaState === 'idle'}
{:else if $papaState === 'error'}
<h2 class="text-center text-[--text-normal]">An error occured.<br /> Please retry initialization...</h2>
<button
aria-label="Retry initializing"
on:click={() => $plugin.initPapa()}
class="h-8 rounded-l-md px-4 py-2 transition duration-300 ease-in-out hover:bg-[--text-accent-hover]"
use:icon={'refresh-cw'}
/>
{:else if $papaState === 'mode-changed'}
<h2 class="text-center text-[--text-normal]">Reinitialize Smart Second Brain <br />with {$isIncognitoMode ? 'Ollama' : 'OpenAI'}.</h2>
<button
aria-label="Initialize"
on:click={() => $plugin.initPapa()}
class="h-8 rounded-l-md px-4 py-2 transition duration-300 ease-in-out hover:bg-[--text-accent-hover]"
use:icon={'play'}
/>
{:else}
{#if $isIncognitoMode}
<h2 class="mb-0 text-center text-[--text-normal]">Ollama</h2>
<p class="mt-1 text-center text-[--text-normal]">Chat via {$plugin.data.ollamaGenModel.model}</p>
Expand Down Expand Up @@ -99,14 +115,6 @@
<DropdownComponent selected={$plugin.data.assistantLanguage} options={languages} changeFunc={setAssistantLanguage} />
</div>
</div>
{:else if $papaState === 'error'}
<h2 class="text-center text-[--text-normal]">An error occured.<br /> Please retry initialization...</h2>
<button
aria-label="Retry initializing"
on:click={() => $plugin.initPapa()}
class="h-8 rounded-l-md px-4 py-2 transition duration-300 ease-in-out hover:bg-[--text-accent-hover]"
use:icon={'refresh-cw'}
/>
{/if}
{/if}
<div class="absolute bottom-0 z-10 flex w-full justify-center {$isChatInSidebar ? 'bg-[--background-secondary]' : 'bg-[--background-primary]'}">
Expand Down
1 change: 0 additions & 1 deletion src/components/Onboarding/Onboarding.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
</script>

<div class="flex h-full flex-col pt-10">
<div class="flex w-full justify-center *:!h-[--icon-xl] *:!w-[--icon-xl]" use:icon={'brain-circuit'} />
<h1 class="text-center text-[--text-normal]">Setup</h1>
<div class="flex w-full justify-center">
<SliderComponent options={installOptions} bind:selected />
Expand Down
39 changes: 18 additions & 21 deletions src/components/Settings/Settings.svelte
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<script lang="ts">
import TextComponent from '../base/Text.svelte';
import FFExcludeComponent from './FFExclude.svelte';
import { plugin, isIncognitoMode } from '../../store';
import { plugin, isIncognitoMode, papaState, type PapaState } from '../../store';
import { Notice, requestUrl, setIcon } from 'obsidian';
import { onMount } from 'svelte';
import SettingContainer from './SettingContainer.svelte';
Expand All @@ -10,8 +10,7 @@
import ToggleComponent from '../base/Toggle.svelte';
import { DEFAULT_SETTINGS } from '../../main';
import ButtonComponent from '../base/Button.svelte';
import { changeOllamaBaseUrl, getOllamaGenModel, isOllamaRunning, ollamaEmbedChange } from '../../controller/Ollama';
import { isAPIKeyValid } from '../../controller/OpenAI';
import { changeOllamaBaseUrl, getOllamaGenModel, ollamaEmbedChange } from '../../controller/Ollama';
import { t } from 'svelte-i18n';
import Log from '../../logging';
Expand Down Expand Up @@ -138,20 +137,6 @@
$plugin.saveSettings();
};
const initializeSecondBrain = async () => {
if ($isIncognitoMode && !(await isOllamaRunning())) {
new Notice('Please make sure Ollama is running before initializing Smart Second Brain.', 5000);
return;
}
if (!$isIncognitoMode && !(await isAPIKeyValid())) {
new Notice('Please make sure OpenAI API Key is valid before initializing Smart Second Brain.', 5000);
return;
}
await $plugin.initPapa();
};
async function changeDocNum(docNum: number) {
if (docNum < 1 || !docNum) {
docNum = DEFAULT_SETTINGS.docRetrieveNum;
Expand All @@ -174,10 +159,21 @@
$plugin.saveSettings();
};
let oldPapaState: PapaState;
function toggleIncognitoMode() {
if ($papaState === 'running') return new Notice('Please wait for the current query to finish', 4000);
else if ($papaState === 'indexing' || $papaState === 'indexing-paused' || $papaState === 'loading')
return new Notice('Please wait for the indexing to finish', 4000);
$isIncognitoMode = !$isIncognitoMode;
$plugin.data.isIncognitoMode = $isIncognitoMode;
$plugin.saveSettings();
if ($papaState === 'mode-changed') {
// Already in mode-changed state so we restore the previous state (there are only two states)
$papaState = oldPapaState;
return;
}
oldPapaState = $papaState;
$papaState = 'mode-changed';
}
</script>

Expand Down Expand Up @@ -279,10 +275,6 @@
</SettingContainer>
{/if}
{/if}
<!-- Initialize Second Brain -->
<SettingContainer settingName="">
<ButtonComponent buttonText={$t('init_s2b')} styles="mod-cta" changeFunc={initializeSecondBrain} />
</SettingContainer>
</div>
<!-- Advanced Settings -->
<details>
Expand All @@ -291,6 +283,11 @@
<SettingContainer settingName="Num. of Docs to Retrieve">
<TextComponent inputType="number" bind:this={componentDocNum} changeFunc={(docNum) => changeDocNum(parseInt(docNum))} />
</SettingContainer>
<!-- Clear Plugin Data -->
<SettingContainer settingName="Clear Plugin Data">
<!-- TODO Add a warning modal -->
<ButtonComponent buttonText="Clear" styles="mod-warning" changeFunc={() => $plugin.clearPluginData()} />
</SettingContainer>
<!-- Debugging -->
<SettingContainer settingName="Debugging" isHeading={true} />
<SettingContainer settingName="Langsmith Key">
Expand Down
5 changes: 3 additions & 2 deletions src/controller/Messages.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { plugin as p, chatHistory as history, type ChatMessage, isEditing, chatInput, isEditingAssistantMessage } from '../store';
import { get } from 'svelte/store';
import { MarkdownRenderer, Notice, setIcon } from 'obsidian';
import { runSecondBrainFromChat } from './runSecondBrain';
import { canRunSecondBrain, runSecondBrain } from './runSecondBrain';
import { DEFAULT_SETTINGS } from '../main';
import { nanoid } from 'nanoid';

Expand Down Expand Up @@ -115,12 +115,13 @@ export const toClipboard = (messageText: string) => {
};

export const redoGeneration = async (message: ChatMessage) => {
if (!canRunSecondBrain()) return;
const plugin = get(p);
const chatHistory = get(history);
const targetIndex = chatHistory.indexOf(message) - 1;
const userQuery = chatHistory[targetIndex];
history.set(chatHistory.slice(0, targetIndex));
await runSecondBrainFromChat(plugin.data.isUsingRag, userQuery.content);
await runSecondBrain(plugin.data.isUsingRag, userQuery.content);
};

export function editMessage(message: ChatMessage, textarea: HTMLTextAreaElement): string {
Expand Down
19 changes: 17 additions & 2 deletions src/controller/runSecondBrain.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
import { get } from 'svelte/store';
import { nanoid } from 'nanoid';
import { chatHistory as cH, isEditing, plugin as p, serializeChatHistory, papaState } from '../store';
import { Notice } from 'obsidian';

export async function runSecondBrainFromChat(isRAG: boolean, userQuery: string) {
export const canRunSecondBrain = () => {
if (get(papaState) === 'running') return new Notice('Please wait for the current query to finish', 4000) && false;
else if (get(papaState) === 'indexing' || get(papaState) === 'indexing-paused' || get(papaState) === 'loading')
return new Notice('Please wait for the indexing to finish', 4000) && false;
else if (get(papaState) === 'error') return new Notice('Please wait for the error to resolve', 4000) && false;
else if (get(papaState) !== 'idle') return new Notice('Please initialize your Smart Second Brain first', 4000) && false;
return true;
};

export async function runSecondBrain(isRAG: boolean, userQuery: string) {
papaState.set('running');
const plugin = get(p);

Expand All @@ -23,7 +33,12 @@ export async function runSecondBrainFromChat(isRAG: boolean, userQuery: string)

for await (const response of responseStream) {
cH.set([...chatHistory, { role: 'Assistant', content: response.content, id: nanoid() }]);
if (get(papaState) === 'running-stopped') break;
if (get(papaState) === 'running-stopped') {
if (response.status !== 'Generating') cH.set([...chatHistory, { role: 'Assistant', content: 'Stopped', id: nanoid() }]);
papaState.set('idle');
plugin.chatView.save();
return; // when used break it somehow returns the whole function
}
}
plugin.chatView.save();
papaState.set('idle');
Expand Down
11 changes: 11 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,8 @@ export default class SecondBrainPlugin extends Plugin {

async initPapa() {
if (get(papaState) === 'running') return new Notice('Smart Second Brain is still running.', 4000);
else if (get(papaState) === 'indexing' || get(papaState) === 'indexing-paused' || get(papaState) === 'loading')
return new Notice('Please wait for the indexing to finish', 4000);
else if (this.data.isIncognitoMode && !(await isOllamaRunning()))
return new Notice('Please make sure Ollama is running before initializing Smart Second Brain.', 4000);
else if (!this.data.isIncognitoMode && !(await isAPIKeyValid()))
Expand Down Expand Up @@ -162,6 +164,7 @@ export default class SecondBrainPlugin extends Plugin {
this.saveVectorStoreData();
if (get(papaIndexingProgress) === 100) {
new Notice('Smart Second Brain initialized.', 2000);
papaIndexingProgress.set(0);
papaState.set('idle');
}
}
Expand Down Expand Up @@ -320,6 +323,14 @@ export default class SecondBrainPlugin extends Plugin {
await this.activateView(newChatFile);
}

async clearPluginData() {
await this.saveData({});
const files = (await this.app.vault.adapter.list(normalizePath(this.manifest.dir))).files;
for (const file of files) {
if (file.endsWith('vector-store.bin')) await this.app.vault.adapter.remove(file);
}
}

registerMonkeyPatches() {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const self = this;
Expand Down
2 changes: 1 addition & 1 deletion src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const chatInput = writable<string>('');
export const isOnboarded = writable<boolean>(false);
export const isChatInSidebar = writable<boolean>(true);

type PapaState = 'idle' | 'loading' | 'indexing' | 'indexing-paused' | 'running' | 'running-stopped' | 'error' | 'uninitialized';
export type PapaState = 'idle' | 'loading' | 'indexing' | 'indexing-paused' | 'running' | 'running-stopped' | 'error' | 'uninitialized' | 'mode-changed';
export const papaState = writable<PapaState>('uninitialized');
export const papaIndexingProgress = writable<number>(0);

Expand Down

0 comments on commit 22a137e

Please sign in to comment.