Merge branch 'main' into test/1886-chat-dock-checks
This commit is contained in:
commit
cdae23d7e9
12 files changed
+307
-28
No files matched your search
@@ -230,7 +230,7 @@ func (a *LocalChatAdapter) runStreamedTurn(ctx context.Context, in Inbound, id s
|
||||
run := func(turnCtx context.Context) ChatEvent {
|
||||
reply, err := a.Router.streamTurn(turnCtx, in, stream)
|
||||
if err != nil {
|
||||
return ChatEvent{Kind: "error", Text: err.Error(), SessionID: id}
|
||||
return ChatEvent{Kind: "error", Text: turnFailureText(err), SessionID: id}
|
||||
}
|
||||
resolvedID := id
|
||||
if resolved, err := a.Router.ResolveSessionKey(turnCtx, in); err == nil {
|
||||
@@ -306,7 +306,7 @@ func (a *LocalChatAdapter) prelude(ctx context.Context, in Inbound, id string) s
|
||||
}
|
||||
ready, mine, err := a.Router.CollectTurn(ctx, in)
|
||||
if err != nil {
|
||||
return streamPrelude{event: &ChatEvent{Kind: "error", Text: err.Error(), SessionID: id}}
|
||||
return streamPrelude{event: &ChatEvent{Kind: "error", Text: turnFailureText(err), SessionID: id}}
|
||||
}
|
||||
return streamPrelude{ready: ready, proceeds: mine}
|
||||
}
|
||||
|
||||
@@ -580,7 +580,7 @@ func (r *TurnRunner) failTurn(ctx context.Context, turn TurnRecord, cause error)
|
||||
} else {
|
||||
turn.Status = TurnStatusFailed
|
||||
}
|
||||
turn.Error = cause.Error()
|
||||
turn.Error = turnFailureText(cause)
|
||||
turn.UpdatedAt = time.Now().UTC()
|
||||
if r.Log != nil {
|
||||
level := slog.LevelError
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/samcharles93/ai-sdk/chat"
|
||||
)
|
||||
|
||||
// turnFailureText is what a chat reader sees when a turn fails. The cause
|
||||
// carries provider bodies, URLs and wrapping that belong in the log, which
|
||||
// failTurn writes, not in front of whoever is chatting.
|
||||
func turnFailureText(err error) string {
|
||||
switch {
|
||||
case errors.Is(err, chat.ErrRateLimited):
|
||||
return "the model provider is refusing requests (rate limit or spending cap). Try again later, or switch model with /model."
|
||||
case errors.Is(err, chat.ErrAuthFailed):
|
||||
return "the model provider rejected Archie's credentials. Check the provider key in settings."
|
||||
case errors.Is(err, chat.ErrProviderUnavailable):
|
||||
return "the model provider is unavailable. Try again in a moment."
|
||||
case errors.Is(err, chat.ErrContextLength):
|
||||
return "this conversation is too long for the model. Start a new chat, or shorten it with /compress."
|
||||
case errors.Is(err, chat.ErrUnsupportedContent):
|
||||
return "the model can't read one of the attachments. Remove it, or switch model with /model."
|
||||
case errors.Is(err, context.DeadlineExceeded):
|
||||
return "the model took too long to answer. Try again."
|
||||
default:
|
||||
return "something went wrong on Archie's side. Try again; the gateway log has the cause."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/ai-sdk/chat"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// A failed turn shows the reader what to do, never the provider's response
|
||||
// body or the error's wrapping.
|
||||
func TestStreamedTurnFailureHidesCause(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
cause error
|
||||
want string
|
||||
}{
|
||||
{name: "spending cap", cause: chat.ErrRateLimited, want: "rate limit or spending cap"},
|
||||
{name: "bad key", cause: chat.ErrAuthFailed, want: "credentials"},
|
||||
{name: "unknown", cause: errors.New("dial tcp 10.0.0.1:5432: refused"), want: "gateway log"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
raw := fmt.Errorf(`llm chat stream: gemini: status 429: {"message":"https://ai.studio/spend"}: %w`, tc.cause)
|
||||
router := &Router{LLMStream: func(context.Context, Inbound, TurnStream) (string, error) { return "", raw }}
|
||||
adapter := &LocalChatAdapter{Router: router}
|
||||
events := make(chan ChatEvent, 32)
|
||||
go adapter.runStreamedTurn(context.Background(), Inbound{Message: messaging.Message{Text: "hi"}}, "s1", events)
|
||||
for event := range events {
|
||||
if event.Kind != "error" {
|
||||
continue
|
||||
}
|
||||
for _, leak := range []string{"gemini", "429", "ai.studio", "10.0.0.1", "llm chat stream"} {
|
||||
if strings.Contains(event.Text, leak) {
|
||||
t.Fatalf("error text %q exposes %q", event.Text, leak)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(event.Text, tc.want) {
|
||||
t.Fatalf("error text %q, want it to mention %q", event.Text, tc.want)
|
||||
}
|
||||
return
|
||||
}
|
||||
t.Fatal("no error event")
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -100,6 +100,9 @@ func splitLegacyChannelSettings(orgID string, stored []byte) (rewritten []byte,
|
||||
return nil, telegramConnection{}, false, fmt.Errorf("decode telegram: %w", err)
|
||||
}
|
||||
delete(doc, "telegram")
|
||||
// A document old enough to carry telegram can also carry the per-channel
|
||||
// models that model aliases replaced, which the current schema rejects.
|
||||
delete(doc, "models")
|
||||
if orgID == storecontract.DefaultOrgID {
|
||||
moved = telegramConnection{Token: legacy.TokenRef, Users: legacy.AllowedUserIDs}
|
||||
} else if len(legacy.AllowedUserIDs) > 0 {
|
||||
|
||||
@@ -15,6 +15,8 @@ import {
|
||||
commandSelection,
|
||||
commandSpecs,
|
||||
addTaskTag,
|
||||
clearPageTag,
|
||||
pageTag,
|
||||
composerText,
|
||||
editQueued,
|
||||
menuTrigger,
|
||||
@@ -219,7 +221,16 @@ function onKeydown(event: KeyboardEvent): void {
|
||||
</Tooltip>
|
||||
</li>
|
||||
</ul>
|
||||
<ul v-if="taskTags.length" aria-label="Attached tasks" class="mb-2 flex flex-wrap gap-1">
|
||||
<ul v-if="pageTag || taskTags.length" aria-label="Message context" class="mb-2 flex flex-wrap gap-1">
|
||||
<li
|
||||
v-if="pageTag"
|
||||
class="flex max-w-full items-center gap-1 rounded-md border border-border bg-muted px-2 py-0.5 text-label"
|
||||
>
|
||||
<span class="truncate">{{ pageTag.label }}</span>
|
||||
<Button variant="ghost" size="icon" class="size-5" aria-label="Remove page context" @click="clearPageTag"
|
||||
><X
|
||||
/></Button>
|
||||
</li>
|
||||
<li
|
||||
v-for="tag in taskTags"
|
||||
:key="tag.id"
|
||||
@@ -249,7 +260,7 @@ function onKeydown(event: KeyboardEvent): void {
|
||||
aria-controls="slash-palette"
|
||||
:aria-expanded="isCommandMenuOpen ? 'true' : 'false'"
|
||||
:aria-activedescendant="isCommandMenuOpen && commandMatches.length ? `slash-palette-option-${commandSelection}` : undefined"
|
||||
class="max-h-40 min-h-11 flex-1 resize-none rounded-none border-0 bg-transparent! px-0 py-1 text-label shadow-none focus-visible:ring-0"
|
||||
class="max-h-40 min-h-11 flex-1 resize-none rounded-none border-0 bg-transparent! px-0 py-1 text-label pointer-coarse:text-base shadow-none focus-visible:ring-0"
|
||||
@input="onInput"
|
||||
@keydown="onKeydown"
|
||||
/>
|
||||
|
||||
+63
-12
@@ -1,15 +1,18 @@
|
||||
<script setup lang="ts">
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { ChevronDown, ChevronUp } from "@lucide/vue";
|
||||
import { useMediaQuery, useStorage, useWindowSize } from "@vueuse/core";
|
||||
import { useEventListener, useMediaQuery, useStorage, useWindowSize } from "@vueuse/core";
|
||||
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from "vue";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useLiveResource } from "@/stores/session";
|
||||
import { cn } from "@/lib/utils";
|
||||
import ChatBar from "./ChatBar.vue";
|
||||
import ChatComposer from "./ChatComposer.vue";
|
||||
import ChatTranscript from "./ChatTranscript.vue";
|
||||
import { composerText, escapeOwnedByLayer, isSending, useChat } from "./state";
|
||||
import { composerText, escapeOwnedByLayer, isSending, reloadTranscript, useChat } from "./state";
|
||||
import { setDockOpen, unseenCount } from "./unseen";
|
||||
|
||||
/**
|
||||
* Chat is a bar docked at the bottom of every page, not a route: the operator
|
||||
@@ -26,6 +29,9 @@ import { composerText, escapeOwnedByLayer, isSending, useChat } from "./state";
|
||||
* Dragging the header to an edge pins it; dragging it away, or double-clicking
|
||||
* the header, unpins it. The side and width are remembered per browser.
|
||||
*
|
||||
* On a phone the bar rides above the on-screen keyboard, which iOS does not
|
||||
* resize the page for, and swiping down on the conversation header hides it.
|
||||
*
|
||||
* It stays mounted, so the session and any turn in flight survive a navigation.
|
||||
* It is mounted outside the app shell: `.shell`'s backdrop-filter makes it a
|
||||
* containing block for `position: fixed`, so a bar nested inside would anchor to
|
||||
@@ -33,7 +39,12 @@ import { composerText, escapeOwnedByLayer, isSending, useChat } from "./state";
|
||||
*/
|
||||
useChat();
|
||||
|
||||
// A task this conversation started reports its outcome into it. The dock stays
|
||||
// mounted while collapsed, so a reply that lands then is still read and counted.
|
||||
useLiveResource("chat", () => void reloadTranscript());
|
||||
|
||||
const expanded = ref(false);
|
||||
watch(expanded, setDockOpen, { immediate: true });
|
||||
const MIN_WIDTH = 320;
|
||||
const EDGE = 64;
|
||||
type Side = "left" | "right";
|
||||
@@ -49,6 +60,20 @@ const width = computed(() =>
|
||||
Math.round(Math.min(Math.max(saved.value.width, MIN_WIDTH), Math.max(MIN_WIDTH, Math.min(720, viewport.value - 480)))),
|
||||
);
|
||||
const side = computed(() => (desktop.value && expanded.value ? saved.value.side : null));
|
||||
// The part of the layout viewport the on-screen keyboard covers, and the height
|
||||
// left above it. Fixed elements stay anchored to the layout viewport, so without
|
||||
// this the bar sits under the keyboard.
|
||||
const keyboard = ref(0);
|
||||
const visibleHeight = ref(window.innerHeight);
|
||||
function followViewport(): void {
|
||||
const vv = window.visualViewport;
|
||||
keyboard.value = vv ? Math.max(0, Math.round(window.innerHeight - vv.height - vv.offsetTop)) : 0;
|
||||
visibleHeight.value = vv ? vv.height : window.innerHeight;
|
||||
}
|
||||
useEventListener(() => window.visualViewport, ["resize", "scroll"], followViewport);
|
||||
const phoneBottom = computed(() =>
|
||||
keyboard.value > 0 ? `${keyboard.value + 8}px` : "max(0.5rem, env(safe-area-inset-bottom))",
|
||||
);
|
||||
const composer = ref<InstanceType<typeof ChatComposer> | null>(null);
|
||||
|
||||
// Nothing outside the dock closes it: every navigation control is outside it,
|
||||
@@ -113,12 +138,13 @@ function edgeAt(x: number): Side | null {
|
||||
|
||||
// Pointer travel before a press on the header becomes a drag, so a click or a
|
||||
// double-click on it never moves the dock.
|
||||
const INTERACTIVE = "button, a, input, select, textarea, [role=combobox]";
|
||||
const DRAG_START = 4;
|
||||
const offset = ref<{ x: number; y: number } | null>(null);
|
||||
const target = ref<Side | null>(null);
|
||||
function startDrag(event: PointerEvent): void {
|
||||
if (!desktop.value || event.button !== 0) return;
|
||||
if ((event.target as HTMLElement).closest("button, a, input, select, textarea, [role=combobox]")) return;
|
||||
if (event.button !== 0 || (event.target as HTMLElement).closest(INTERACTIVE)) return;
|
||||
if (!desktop.value) return startSwipe(event);
|
||||
const grip = event.currentTarget as HTMLElement;
|
||||
const { clientX: x0, clientY: y0 } = event;
|
||||
grip.setPointerCapture(event.pointerId);
|
||||
@@ -141,8 +167,27 @@ function startDrag(event: PointerEvent): void {
|
||||
grip.addEventListener("pointerup", end);
|
||||
grip.addEventListener("pointercancel", end);
|
||||
}
|
||||
// A downward flick on the header hides the conversation. It must be mostly
|
||||
// vertical so a sideways slip does not collapse it.
|
||||
const SWIPE = 48;
|
||||
function startSwipe(event: PointerEvent): void {
|
||||
const grip = event.currentTarget as HTMLElement;
|
||||
const { clientX: x0, clientY: y0 } = event;
|
||||
const end = (e: PointerEvent): void => {
|
||||
grip.removeEventListener("pointerup", end);
|
||||
grip.removeEventListener("pointercancel", end);
|
||||
const dy = e.clientY - y0;
|
||||
if (e.type === "pointerup" && dy >= SWIPE && dy > Math.abs(e.clientX - x0) * 1.5) {
|
||||
// The keyboard is for the composer, which is no longer in front of it.
|
||||
(document.activeElement as HTMLElement | null)?.blur();
|
||||
expanded.value = false;
|
||||
}
|
||||
};
|
||||
grip.addEventListener("pointerup", end);
|
||||
grip.addEventListener("pointercancel", end);
|
||||
}
|
||||
function togglePin(event: MouseEvent): void {
|
||||
if (!desktop.value || (event.target as HTMLElement).closest("button, a, input, select, textarea, [role=combobox]")) return;
|
||||
if (!desktop.value || (event.target as HTMLElement).closest(INTERACTIVE)) return;
|
||||
saved.value.side = saved.value.side ? null : "right";
|
||||
}
|
||||
|
||||
@@ -185,15 +230,15 @@ function usePrompt(text: string): void {
|
||||
<div
|
||||
:class="cn(
|
||||
'pointer-events-none fixed z-40',
|
||||
side ? cn('inset-y-0', side === 'left' ? 'left-0' : 'right-0') : 'inset-x-0 bottom-4 flex justify-center px-3 max-md:bottom-2',
|
||||
side ? cn('inset-y-0', side === 'left' ? 'left-0' : 'right-0') : 'inset-x-0 bottom-4 flex justify-center px-3',
|
||||
)"
|
||||
:style="side ? { width: `${width}px` } : undefined"
|
||||
:style="side ? { width: `${width}px` } : desktop ? undefined : { bottom: phoneBottom }"
|
||||
>
|
||||
<aside
|
||||
ref="dock"
|
||||
aria-label="Chat with Archie"
|
||||
:class="cn(
|
||||
'pointer-events-auto relative flex flex-col border-border-strong bg-popover shadow-[var(--shadow-md)]',
|
||||
'touch-hit pointer-events-auto relative flex flex-col border-border-strong bg-popover shadow-[var(--shadow-md)]',
|
||||
side
|
||||
? cn('h-full w-full', side === 'left' ? 'border-r' : 'border-l')
|
||||
: 'w-full max-w-xl rounded-lg border',
|
||||
@@ -216,11 +261,11 @@ function usePrompt(text: string): void {
|
||||
/>
|
||||
<div
|
||||
v-if="expanded"
|
||||
:class="desktop && 'cursor-grab select-none active:cursor-grabbing'"
|
||||
:class="desktop ? 'cursor-grab select-none active:cursor-grabbing' : 'touch-none'"
|
||||
@pointerdown="startDrag"
|
||||
@dblclick="togglePin"
|
||||
>
|
||||
<div v-if="desktop" class="flex justify-center pt-1.5" aria-hidden="true">
|
||||
<div class="flex justify-center pt-1.5" aria-hidden="true">
|
||||
<span class="h-1 w-8 rounded-full bg-border-strong" />
|
||||
</div>
|
||||
<ChatBar>
|
||||
@@ -240,7 +285,11 @@ function usePrompt(text: string): void {
|
||||
</Tooltip>
|
||||
</ChatBar>
|
||||
</div>
|
||||
<div v-if="expanded" :class="cn('flex min-h-0 flex-col', side ? 'flex-1' : 'h-[min(28rem,55dvh)]')">
|
||||
<div
|
||||
v-if="expanded"
|
||||
:class="cn('flex min-h-0 flex-col', side ? 'flex-1' : 'h-[min(28rem,55dvh)]')"
|
||||
:style="side || desktop ? undefined : { height: `min(28rem, ${Math.round(visibleHeight * 0.55)}px)` }"
|
||||
>
|
||||
<ChatTranscript @prompt="usePrompt" />
|
||||
</div>
|
||||
<div @focusin="expanded = true">
|
||||
@@ -251,10 +300,12 @@ function usePrompt(text: string): void {
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label="Show conversation"
|
||||
:class="cn(unseenCount && 'w-auto gap-1 px-2')"
|
||||
:aria-label="unseenCount ? `Show conversation, ${unseenCount} new` : 'Show conversation'"
|
||||
@click="expanded = true"
|
||||
>
|
||||
<ChevronUp />
|
||||
<Badge v-if="unseenCount" variant="default" aria-hidden="true">{{ unseenCount }}</Badge>
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Show conversation</TooltipContent>
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
<script setup lang="ts">
|
||||
import { ArrowDownIcon } from "@lucide/vue";
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
|
||||
|
||||
import { MessageScrollerButton, useMessageScrollerScrollable } from "@/components/ui/message-scroller";
|
||||
import { setAtEnd, unseenCount } from "./unseen";
|
||||
|
||||
/**
|
||||
* The scroller's jump-to-latest button. It reads where the reader is for the
|
||||
* unseen count and says how many replies are waiting below.
|
||||
*
|
||||
* The scroller measures on the frames after it mounts, and until then it
|
||||
* reports "not scrollable", which would look like the end. The reader counts
|
||||
* as at the end only once it has measured.
|
||||
*/
|
||||
const scrollable = useMessageScrollerScrollable();
|
||||
const measured = ref(false);
|
||||
let frame = 0;
|
||||
onMounted(() => {
|
||||
frame = requestAnimationFrame(() => {
|
||||
frame = requestAnimationFrame(() => {
|
||||
measured.value = true;
|
||||
});
|
||||
});
|
||||
});
|
||||
onUnmounted(() => {
|
||||
cancelAnimationFrame(frame);
|
||||
setAtEnd(false);
|
||||
});
|
||||
watch(
|
||||
() => measured.value && !scrollable.value.end,
|
||||
(end) => setAtEnd(end),
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
const label = computed(() => `${unseenCount.value} new ${unseenCount.value === 1 ? "reply" : "replies"}`);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<MessageScrollerButton :size="unseenCount ? 'sm' : 'icon-sm'" :class="unseenCount ? 'gap-1.5 whitespace-nowrap' : undefined">
|
||||
<ArrowDownIcon />
|
||||
<template v-if="unseenCount">{{ label }}</template>
|
||||
<span v-else class="sr-only">Scroll to end</span>
|
||||
</MessageScrollerButton>
|
||||
</template>
|
||||
@@ -4,18 +4,17 @@ import { computed } from "vue";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
MessageScroller,
|
||||
MessageScrollerButton,
|
||||
MessageScrollerContent,
|
||||
MessageScrollerItem,
|
||||
MessageScrollerProvider,
|
||||
MessageScrollerViewport,
|
||||
} from "@/components/ui/message-scroller";
|
||||
import { useLiveResource } from "@/stores/session";
|
||||
import ChatAskCard from "./ChatAskCard.vue";
|
||||
import ChatBubble from "./ChatBubble.vue";
|
||||
import ChatChooseCard from "./ChatChooseCard.vue";
|
||||
import ChatUpdateCard from "./ChatUpdateCard.vue";
|
||||
import ChatEmptyState from "./ChatEmptyState.vue";
|
||||
import ChatJumpButton from "./ChatJumpButton.vue";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import {
|
||||
@@ -27,7 +26,6 @@ import {
|
||||
sessionError,
|
||||
streamingTurn,
|
||||
type ChatMessage,
|
||||
reloadTranscript,
|
||||
} from "./state";
|
||||
|
||||
/**
|
||||
@@ -78,9 +76,6 @@ const rows = computed(() => {
|
||||
},
|
||||
];
|
||||
});
|
||||
|
||||
// A task this conversation started reports its outcome into it.
|
||||
useLiveResource("chat", () => void reloadTranscript());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -141,7 +136,7 @@ useLiveResource("chat", () => void reloadTranscript());
|
||||
</MessageScrollerContent>
|
||||
</MessageScrollerViewport>
|
||||
|
||||
<MessageScrollerButton />
|
||||
<ChatJumpButton />
|
||||
</MessageScroller>
|
||||
</MessageScrollerProvider>
|
||||
</template>
|
||||
+35
-4
@@ -1,6 +1,7 @@
|
||||
import { computed, onMounted, onUnmounted, ref, watch, type Ref } from "vue";
|
||||
|
||||
import { api } from "@/lib/api";
|
||||
import { router } from "@/router";
|
||||
import { randomUUID } from "@/lib/uuid";
|
||||
import { channelID } from "./channel";
|
||||
import { commandCompletions, detectTrigger, taskCompletions, type Completion, type Trigger } from "./commands";
|
||||
@@ -335,7 +336,7 @@ async function sendCommand(
|
||||
channel_id: channelID(),
|
||||
source_id: randomUUID(),
|
||||
text,
|
||||
page: currentPage(),
|
||||
page: sentPage(),
|
||||
});
|
||||
if (!response.body) throw new Error("the chat stream returned no body");
|
||||
const reader = response.body.getReader();
|
||||
@@ -631,9 +632,39 @@ export function moveCommandSelection(delta: number): void {
|
||||
commandSelection.value = (commandSelection.value + delta + length) % length;
|
||||
}
|
||||
|
||||
/** The page the operator asked from, so an answer can be about what they saw. */
|
||||
/** The page the operator is on, without the hash the server never sees. */
|
||||
function currentPage(): string {
|
||||
return location.pathname + location.search || "/";
|
||||
return router.currentRoute.value.fullPath.split("#")[0] || "/";
|
||||
}
|
||||
|
||||
// The page whose tag the operator removed. Navigating elsewhere shows the tag
|
||||
// again, so the dismissal never outlives the page it was made on.
|
||||
const clearedPage = ref("");
|
||||
watch(currentPage, () => {
|
||||
clearedPage.value = "";
|
||||
});
|
||||
|
||||
/** What the next message is about, named for the tag above the composer. */
|
||||
export const pageTag = computed(() => {
|
||||
const page = currentPage();
|
||||
if (page === clearedPage.value) return null;
|
||||
const route = router.currentRoute.value;
|
||||
const label =
|
||||
route.name === "task-detail"
|
||||
? `Task #${route.params.id}`
|
||||
: typeof route.meta.label === "string"
|
||||
? route.meta.label
|
||||
: page;
|
||||
return { page, label };
|
||||
});
|
||||
|
||||
export function clearPageTag(): void {
|
||||
clearedPage.value = currentPage();
|
||||
}
|
||||
|
||||
/** The page sent with a message: the tag's page, or none once it is cleared. */
|
||||
function sentPage(): string | undefined {
|
||||
return pageTag.value?.page;
|
||||
}
|
||||
|
||||
export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
|
||||
@@ -731,7 +762,7 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
|
||||
channel_id: channelID(),
|
||||
source_id: turn.sourceID,
|
||||
text: turn.text,
|
||||
page: currentPage(),
|
||||
page: sentPage(),
|
||||
voice: turn.voice,
|
||||
},
|
||||
{ signal: ctrl.signal },
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { computed, ref, watch } from "vue";
|
||||
|
||||
import { isLoadingSession, messages, type ChatMessage } from "./state";
|
||||
|
||||
/**
|
||||
* Counts the replies the operator has not seen. A reply is seen once the
|
||||
* conversation is open and scrolled to its end; one that lands before that,
|
||||
* such as a finished task's outcome while the dock is collapsed or the reader
|
||||
* is scrolled up, adds to the count until then.
|
||||
*
|
||||
* It counts replies by position, not by id: a streamed reply is appended
|
||||
* locally without an id and a later reload returns it with one, and that must
|
||||
* not count twice.
|
||||
*/
|
||||
const dockOpen = ref(false);
|
||||
const atEnd = ref(false);
|
||||
const seen = ref(0);
|
||||
|
||||
function isReply(message: ChatMessage): boolean {
|
||||
// Cards the operator's own command produced are not something Archie said.
|
||||
return (message.from ?? message.From ?? "") !== "web" && !message.update && !message.choose;
|
||||
}
|
||||
|
||||
const total = computed(() => messages.value.filter(isReply).length);
|
||||
const viewing = computed(() => dockOpen.value && atEnd.value);
|
||||
|
||||
export const unseenCount = computed(() => Math.max(0, total.value - seen.value));
|
||||
|
||||
// Opening or switching a conversation loads it, which is not news; a reload
|
||||
// that drops a message must also lower the mark so the next reply still counts.
|
||||
watch(
|
||||
[total, viewing, isLoadingSession],
|
||||
([count, watching, loading], [, , wasLoading]) => {
|
||||
if (watching || loading || wasLoading || count < seen.value) seen.value = count;
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
/** The dock reports whether the conversation is open above the composer. */
|
||||
export function setDockOpen(open: boolean): void {
|
||||
dockOpen.value = open;
|
||||
}
|
||||
|
||||
/** The scroller's jump button reports whether the reader is at the end. */
|
||||
export function setAtEnd(end: boolean): void {
|
||||
atEnd.value = end;
|
||||
}
|
||||
@@ -351,3 +351,19 @@
|
||||
transition-duration: 0.01ms !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* Widens a control's tap area to 44px on a phone without changing how it looks
|
||||
or what space it takes. Apply it to a container of buttons. */
|
||||
@utility touch-hit {
|
||||
@media (max-width: 767px) {
|
||||
& button:not(.absolute) {
|
||||
position: relative;
|
||||
}
|
||||
& button::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset-block: min(0px, calc((100% - 44px) / 2));
|
||||
inset-inline: min(0px, calc((100% - 44px) / 2));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user