repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
hyperdx
github_2023
typescript
108
hyperdxio
MikeShi42
@@ -127,54 +210,80 @@ const buildEventSlackMessage = ({ const fireChannelEvent = async ({
Just realizing.. why didn't we call this `fireChannelAlert`?
hyperdx
github_2023
typescript
108
hyperdxio
MikeShi42
@@ -127,54 +210,80 @@ const buildEventSlackMessage = ({ const fireChannelEvent = async ({ alert, - logView, - totalCount, + dashboard, + endTime, group, + logView, startTime, - endTime, + totalCount, + windowSizeInMins, }: { - alert: IAlert; - logView: Awaited<ReturnType<typeof getLogViewEnhanced>>; - totalCount: number; + alert: AlertDocument; + logView: Awaited<ReturnType<typeof getLogViewEnhanced>> | null; + dashboard: {
curious why build a one-off as opposed to being consistent with the dashboard schema?
hyperdx
github_2023
typescript
108
hyperdxio
MikeShi42
@@ -58,25 +56,110 @@ export const buildLogSearchLink = ({ return url.toString(); }; -const buildEventSlackMessage = ({ +// TODO: should link to the chart instead +export const buildChartLink = ({ + dashboardId, + endTime, + granularity, + startTime, +}: { + dashboardId: string; + endTime: Date; + granularity: string; + startTime: Date; +}) => { + const url = new URL(`${config.FRONTEND_URL}/dashboards/${dashboardId}`); + const queryParams = new URLSearchParams({ + from: startTime.getTime().toString(),
doesn't this build a pretty terrible dashboard where you only get 1 data point per graph? I think in the URL we should have a time range that's probably like +/- 7*granularity so you get at least 14 data points instead of just 1
hyperdx
github_2023
others
109
hyperdxio
MikeShi42
@@ -31,6 +31,7 @@ "esbuild": "^0.14.47", "fuse.js": "^6.6.2", "immer": "^9.0.21", + "jotai": "^2.5.1",
ah it finally made its way into the project... @joelseq I think you'll enjoy this 😂
hyperdx
github_2023
typescript
109
hyperdxio
MikeShi42
@@ -0,0 +1,63 @@ +import * as React from 'react'; +import { atom, useAtomValue, useSetAtom } from 'jotai'; +import Modal from 'react-bootstrap/Modal'; +import Button from 'react-bootstrap/Button'; + +type ConfirmAtom = { + message: string; + confirmLabel?: string; + onConfirm: () => void; + onClose?: () => void; +} | null; + +const confirmAtom = atom<ConfirmAtom>(null); + +export const useConfirm = () => { + const setConfirm = useSetAtom(confirmAtom); + + return React.useCallback( + async (message: string, confirmLabel?: string): Promise<boolean> => { + return new Promise(resolve => { + setConfirm({ + message, + confirmLabel, + onConfirm: () => { + resolve(true); + setConfirm(null); + }, + onClose: () => { + resolve(false); + setConfirm(null); + }, + }); + }); + }, + [setConfirm], + ); +}; + +export const useConfirmModal = () => { + const confirm = useAtomValue(confirmAtom); + const setConfirm = useSetAtom(confirmAtom); + + const handleClose = React.useCallback(() => { + confirm?.onClose?.(); + setConfirm(null); + }, [confirm, setConfirm]); + + return confirm ? ( + <Modal show onHide={handleClose}>
Personally I'd prefer a tooltip next to the action button but can see how this is faster to implement rn
hyperdx
github_2023
typescript
109
hyperdxio
MikeShi42
@@ -0,0 +1,63 @@ +import * as React from 'react'; +import { atom, useAtomValue, useSetAtom } from 'jotai'; +import Modal from 'react-bootstrap/Modal'; +import Button from 'react-bootstrap/Button'; + +type ConfirmAtom = { + message: string; + confirmLabel?: string; + onConfirm: () => void; + onClose?: () => void; +} | null; + +const confirmAtom = atom<ConfirmAtom>(null); + +export const useConfirm = () => { + const setConfirm = useSetAtom(confirmAtom); + + return React.useCallback( + async (message: string, confirmLabel?: string): Promise<boolean> => { + return new Promise(resolve => {
new pattern learned for me today 🤯
hyperdx
github_2023
typescript
104
hyperdxio
wrn14897
@@ -1139,8 +1139,8 @@ export const getSessions = async ({ ORDER BY maxTimestamp DESC LIMIT ?, ?`, [ - SqlString.raw(buildSearchColumnName('string', 'component')), - SqlString.raw(buildSearchColumnName('string', 'rum_session_id')), + SqlString.raw(buildSearchColumnName('string', 'component') || ''), + SqlString.raw(buildSearchColumnName('string', 'rum_session_id') || ''),
I think we should probably throw if these fields don't exist
hyperdx
github_2023
typescript
104
hyperdxio
wrn14897
@@ -175,7 +175,7 @@ export class SQLSerializer implements Serializer { } if (propertyType != null) { - column = buildSearchColumnName(propertyType, field); + column = buildSearchColumnName(propertyType, field) || '';
`column` can be null in this case
hyperdx
github_2023
typescript
104
hyperdxio
wrn14897
@@ -161,7 +161,7 @@ const fireChannelEvent = async ({ _id: alert.channel.webhookId, }); // ONLY SUPPORTS SLACK WEBHOOKS FOR NOW - if (webhook.service === 'slack') { + if (webhook?.service === 'slack') {
👍
hyperdx
github_2023
typescript
104
hyperdxio
MikeShi42
@@ -1,210 +1,110 @@ import express from 'express'; -import ms from 'ms'; -import { getHours, getMinutes } from 'date-fns'; +import { z } from 'zod'; +import { validateRequest } from 'zod-express-middleware'; -import Alert, { - AlertChannel, - AlertInterval, - AlertType, - AlertSource, -} from '../../models/alert'; -import * as clickhouse from '../../clickhouse'; -import { SQLSerializer } from '../../clickhouse/searchQueryParser'; +import Alert from '../../models/alert'; import { getTeam } from '../../controllers/team'; import { isUserAuthenticated } from '../../middleware/auth'; +import { + createAlert, + updateAlert, + validateGroupByProperty, +} from '../../controllers/alerts'; const router = express.Router(); -const getCron = (interval: AlertInterval) => { - const now = new Date(); - const nowMins = getMinutes(now); - const nowHours = getHours(now); - - switch (interval) { - case '1m': - return '* * * * *'; - case '5m': - return '*/5 * * * *'; - case '15m': - return '*/15 * * * *'; - case '30m': - return '*/30 * * * *'; - case '1h': - return `${nowMins} * * * *`; - case '6h': - return `${nowMins} */6 * * *`; - case '12h': - return `${nowMins} */12 * * *`; - case '1d': - return `${nowMins} ${nowHours} * * *`; - } -}; +// Input validation +const zChannel = z.object({ + type: z.literal('webhook'), + webhookId: z.string().min(1), +}); -const createAlert = async ({ - channel, - groupBy, - interval, - logViewId, - threshold, - type, -}: { - channel: AlertChannel; - groupBy?: string; - interval: AlertInterval; - logViewId: string; - threshold: number; - type: AlertType; -}) => { - return new Alert({ - channel, - cron: getCron(interval), - groupBy, - interval, - source: AlertSource.LOG, - logView: logViewId, - threshold, - timezone: 'UTC', // TODO: support different timezone - type, - }).save(); -}; +const zLogAlert = z.object({ + source: z.literal('LOG'), + groupBy: z.string().optional(), + logViewId: z.string().min(1), + message: z.string().optional(), +}); -// create an update alert function based off of the above create alert function -const updateAlert = async ({ - channel, - groupBy, - id, - interval, - logViewId, - threshold, - type, -}: { - channel: AlertChannel; - groupBy?: string; - id: string; - interval: AlertInterval; - logViewId: string; - threshold: number; - type: AlertType; -}) => { - return Alert.findByIdAndUpdate( - id, - { - channel, - cron: getCron(interval), - groupBy: groupBy ?? null, - interval, - source: AlertSource.LOG, - logView: logViewId, - threshold, - timezone: 'UTC', // TODO: support different timezone - type, - }, - { - returnDocument: 'after', - }, - ); -}; +const zChartAlert = z.object({ + source: z.literal('CHART'), + chartId: z.string().min(1), + dashboardId: z.string().min(1), +}); -router.post('/', isUserAuthenticated, async (req, res, next) => { - try { +const zAlert = z + .object({ + channel: zChannel, + interval: z.enum(['1m', '5m', '15m', '30m', '1h', '6h', '12h', '1d']), + threshold: z.number().min(1),
They're generally deployed at the same time, in general the app will roll out before the API so it should be safe given the backend I believe will have the stricter validation after the app is rolled out. Though we can also time the deployment pipeline manually if needed.
hyperdx
github_2023
typescript
104
hyperdxio
wrn14897
@@ -34,8 +34,8 @@ const bulkInsert = async ( ); break; default: { - const rrwebEvents = []; - const logs = []; + const rrwebEvents: any[] = []; + const logs: any[] = [];
These two should be ` VectorLog[]` and data below is `VectorLog[]` as well
hyperdx
github_2023
typescript
104
hyperdxio
wrn14897
@@ -139,6 +140,20 @@ router.put( { new: true }, ); + // Delete related alerts + const deletedChartIds = differenceBy(
nit: would be great to add int test for this change (in routers/api/__tests__)
hyperdx
github_2023
typescript
104
hyperdxio
wrn14897
@@ -563,13 +563,13 @@ export const buildMetricsPropertyTypeMappingsModel = async ( // TODO: move this to PropertyTypeMappingsModel export const doesLogsPropertyExist = ( - property: string, - model: LogsPropertyTypeMappingsModel, + property?: string, + model?: LogsPropertyTypeMappingsModel,
I wonder why these two args are optional
hyperdx
github_2023
typescript
104
hyperdxio
wrn14897
@@ -563,13 +563,13 @@ export const buildMetricsPropertyTypeMappingsModel = async ( // TODO: move this to PropertyTypeMappingsModel export const doesLogsPropertyExist = ( - property: string, + property: string | undefined, model: LogsPropertyTypeMappingsModel, ) => { if (!property) { return true; // in this case, we don't refresh the property type mappings } - return isCustomColumn(property) || model.get(property); + return isCustomColumn(property) || model?.get(property);
no need for 'model?'
hyperdx
github_2023
typescript
104
hyperdxio
wrn14897
@@ -0,0 +1,118 @@ +import {
🏆
hyperdx
github_2023
others
84
hyperdxio
wrn14897
@@ -55,3 +55,6 @@ scripts/*.csv # docker docker-compose.prod.yml .volumes + +# jetbrains ide
can remove this
hyperdx
github_2023
others
84
hyperdxio
wrn14897
@@ -203,6 +203,7 @@ services: ports: - 8080:8080 environment: + NEXT_PUBLIC_INGESTOR_API_URL: 'http://ingestor:8002'
the host should be 'localhost'
hyperdx
github_2023
typescript
84
hyperdxio
wrn14897
@@ -38,6 +37,29 @@ export default function TeamPage() { const hasAllowedAuthMethods = team?.allowedAuthMethods != null && team?.allowedAuthMethods.length > 0; + const sentryDsn = useMemo(() => { + if (!team) { + return ''; + } + + try { + const ingestorUrl = new URL(process.env.NEXT_PUBLIC_INGESTOR_API_URL);
This won't work with the prod build since process.env only works at dev env. Need to checkout how we inject custom env var at files including `app/src/config.ts`, `app/Dockerfile`, `otel-collector/config.yaml`, `Makefile` and `.env`
hyperdx
github_2023
typescript
84
hyperdxio
wrn14897
@@ -355,6 +377,23 @@ export default function TeamPage() { )} </> )} + <div className="my-5"> + <h2>Sentry Integration</h2> + <div className="text-muted"> + To setup Sentry integration, copy the following Sentry DSN
I think it would be more clear to paste the doc link or something to tell people what DSN is or how to update it in sentry SDK
hyperdx
github_2023
others
84
hyperdxio
wrn14897
@@ -65,8 +65,15 @@ border-radius: 5px; padding: 0.75rem; font-size: 1.1rem; - font-family: Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, - Bitstream Vera Sans Mono, Courier New, monospace; + font-family:
looks like formatting change only. can rollback it
hyperdx
github_2023
typescript
84
hyperdxio
MikeShi42
@@ -1983,6 +1990,41 @@ const ExceptionSubpanel = ({ )} </CollapsibleSection> <CollapsibleSection title="Breadcrumbs" initiallyCollapsed> + <Table striped bordered hover> + <thead> + <tr> + <th>Type</th> + <th>Category</th> + <th>Description</th> + <th>Level</th> + <th>Time</th> + </tr> + </thead> + <tbody> + {Children.toArray(
I'm a bit unclear what this `toArray` is accomplishing here?
hyperdx
github_2023
typescript
84
hyperdxio
MikeShi42
@@ -40,6 +41,7 @@ import 'react-modern-drawer/dist/index.css'; import { CurlGenerator } from './curlGenerator'; import { Dictionary } from './types'; import { ZIndexContext, useZIndex } from './zIndex'; +import joinTeam from '../pages/join-team';
Probably want to clean up this unused import :)
hyperdx
github_2023
typescript
84
hyperdxio
MikeShi42
@@ -38,6 +37,29 @@ export default function TeamPage() { const hasAllowedAuthMethods = team?.allowedAuthMethods != null && team?.allowedAuthMethods.length > 0; + const sentryDsn = useMemo(() => { + if (!team) { + return ''; + } + + try { + const ingestorUrl = new URL(process.env.NEXT_PUBLIC_INGESTOR_API_URL); + + const sentryDsnParts = [ + ingestorUrl.protocol, + '//', + team.apiKey.replace('-', ''),
I think we'd need `replaceAll` or `/-/g` here
hyperdx
github_2023
typescript
84
hyperdxio
MikeShi42
@@ -38,6 +37,29 @@ export default function TeamPage() { const hasAllowedAuthMethods = team?.allowedAuthMethods != null && team?.allowedAuthMethods.length > 0; + const sentryDsn = useMemo(() => { + if (!team) { + return ''; + } + + try { + const ingestorUrl = new URL(process.env.NEXT_PUBLIC_INGESTOR_API_URL); + + const sentryDsnParts = [ + ingestorUrl.protocol, + '//', + team.apiKey.replace('-', ''), + '@', + ingestorUrl.host, + ingestorUrl.port ? `:${ingestorUrl.port}` : '',
For me `ingestorUrl.host` already returns the port so this ended up appending the port twice. We can probably just use `host` on its own since it already includes the port.
hyperdx
github_2023
typescript
84
hyperdxio
MikeShi42
@@ -38,6 +37,29 @@ export default function TeamPage() { const hasAllowedAuthMethods = team?.allowedAuthMethods != null && team?.allowedAuthMethods.length > 0; + const sentryDsn = useMemo(() => { + if (!team) { + return ''; + } + + try { + const ingestorUrl = new URL(process.env.NEXT_PUBLIC_INGESTOR_API_URL); + + const sentryDsnParts = [ + ingestorUrl.protocol, + '//', + team.apiKey.replace('-', ''), + '@', + ingestorUrl.host, + ingestorUrl.port ? `:${ingestorUrl.port}` : '', + ];
It looks like the [Sentry DSN format](https://docs.sentry.io/product/sentry-basics/concepts/dsn-explainer/#the-parts-of-the-dsn) expects a project ID or else the package throws, we can just do `/1` at the end
hyperdx
github_2023
typescript
84
hyperdxio
MikeShi42
@@ -2289,3 +2331,97 @@ export default function LogSidePanel({ </Drawer> ); } + +// TODO: move these to a separate file + +interface BreadcrumbTableItemProps { + breadcrumb: Breadcrumb; +} + +/** + * Renders the type of a breadcrumb and its corresponding type + * @param breadcrumb + * @constructor + */ +function BreadcrumbType({ breadcrumb }: BreadcrumbTableItemProps) { + let icon = <i className="bi bi-info-circle" />; + + switch (breadcrumb.category) { + case 'fetch': { + icon = <i className={'bi bi-arrow-left-right'} />; + break; + } + case 'ui.click': { + icon = <i className="bi bi-mouse" />; + break; + } + case 'navigation': { + icon = <i className="bi bi-geo-alt" />; + break; + } + case 'sentry.transaction': { + icon = <i className="bi bi-gear" />; + } + } + + return <span className="me-2">{icon}</span>; +} + +/** + * Renders the description of a breadcrumb + * + * Based on the type and category of the breadcrumb, displays different information + */ +function BreadcrumbDescription({ breadcrumb }: BreadcrumbTableItemProps) { + if (breadcrumb.type === 'http') { + const { method, status_code, url, ...rest } = breadcrumb.data ?? {}; + + return ( + <div> + {method} {status_code} {url} + <pre className="p-2 bg-grey mt-1"> + <code>{JSON.stringify(rest, null, 2)}</code> + </pre> + </div> + ); + } + + if ( + breadcrumb.category === 'navigation' || + breadcrumb.category === 'console'
It looks like console breadcrumbs capture the message in `breadcrumb.message`, I think we might need some more robust logic here.
hyperdx
github_2023
typescript
84
hyperdxio
MikeShi42
@@ -1983,6 +1990,41 @@ const ExceptionSubpanel = ({ )} </CollapsibleSection> <CollapsibleSection title="Breadcrumbs" initiallyCollapsed> + <Table striped bordered hover> + <thead> + <tr> + <th>Type</th> + <th>Category</th> + <th>Description</th> + <th>Level</th> + <th>Time</th> + </tr> + </thead> + <tbody> + {Children.toArray( + [...breadcrumbs].reverse().map((event, i) => ( + <tr> + <td> + <BreadcrumbType breadcrumb={event} /> + </td> + <td>{event.category}</td> + <td> + <BreadcrumbDescription breadcrumb={event} /> + </td> + <td> + <BreadcrumbLevel breadcrumb={event} /> + </td> + <td> + {format( + new Date(event.timestamp * 1000), + 'MMM d HH:mm:ss.SSS', + )} + </td> + </tr> + )), + )} + </tbody> + </Table>
I think we should delete the breadcrumb list below this table right?
hyperdx
github_2023
typescript
84
hyperdxio
MikeShi42
@@ -2289,3 +2331,97 @@ export default function LogSidePanel({ </Drawer> ); } + +// TODO: move these to a separate file + +interface BreadcrumbTableItemProps { + breadcrumb: Breadcrumb; +} + +/** + * Renders the type of a breadcrumb and its corresponding type + * @param breadcrumb + * @constructor + */ +function BreadcrumbType({ breadcrumb }: BreadcrumbTableItemProps) { + let icon = <i className="bi bi-info-circle" />; + + switch (breadcrumb.category) { + case 'fetch': { + icon = <i className={'bi bi-arrow-left-right'} />; + break; + } + case 'ui.click': { + icon = <i className="bi bi-mouse" />; + break; + } + case 'navigation': { + icon = <i className="bi bi-geo-alt" />; + break; + } + case 'sentry.transaction': { + icon = <i className="bi bi-gear" />; + } + } + + return <span className="me-2">{icon}</span>; +} + +/** + * Renders the description of a breadcrumb + * + * Based on the type and category of the breadcrumb, displays different information + */ +function BreadcrumbDescription({ breadcrumb }: BreadcrumbTableItemProps) { + if (breadcrumb.type === 'http') { + const { method, status_code, url, ...rest } = breadcrumb.data ?? {}; + + return ( + <div> + {method} {status_code} {url} + <pre className="p-2 bg-grey mt-1"> + <code>{JSON.stringify(rest, null, 2)}</code> + </pre> + </div> + ); + } + + if ( + breadcrumb.category === 'navigation' || + breadcrumb.category === 'console' + ) { + return ( + <pre className="p-2 bg-grey">
curious whats the idea to add `bg-grey` for this? It looks a bit weird
hyperdx
github_2023
typescript
88
hyperdxio
MikeShi42
@@ -1,7 +1,7 @@ export const API_SERVER_URL = process.env.NEXT_PUBLIC_SERVER_URL || 'http://localhost:8000'; // NEXT_PUBLIC_API_SERVER_URL can be empty string -export const HDX_API_KEY = process.env.HYPERDX_API_KEY as string; // for nextjs server +export const HDX_API_KEY = process.env.NEXT_PUBLIC_HDX_API_KEY as string; // for nextjs server
let's keep it to `HYPERDX_API_KEY` for now, it looks like the dev docker-compose wasn't updated properly to match the pre-built image compose file. Pre-built: https://github.com/hyperdxio/hyperdx/blob/main/docker-compose.yml#L172 Dev: https://github.com/hyperdxio/hyperdx/blob/main/docker-compose.dev.yml#L207
hyperdx
github_2023
typescript
81
hyperdxio
wrn14897
@@ -9,27 +10,89 @@ import LandingHeader from './LandingHeader'; import * as config from './config'; import api from './api'; +type FormData = { + email: string; + password: string; +}; + export default function AuthPage({ action }: { action: 'register' | 'login' }) { + const isRegister = action === 'register'; + const { + register, + handleSubmit, + formState: { errors, isSubmitting }, + setError, + } = useForm<FormData>({ + reValidateMode: 'onSubmit', + }); const router = useRouter(); const { err, msg } = router.query; const { data: installation } = api.useInstallation(); const verificationSent = msg === 'verify'; - const title = `HyperDX - ${action === 'register' ? 'Sign up' : 'Login'}`; + const title = `HyperDX - ${isRegister ? 'Sign up' : 'Login'}`; useEffect(() => { // If an OSS user accidentally lands on /register after already creating a team // redirect them to login instead - if ( - config.IS_OSS && - installation?.isTeamExisting === true && - action === 'register' - ) { + if (config.IS_OSS && installation?.isTeamExisting === true && isRegister) { router.push('/login'); } - }, [installation, action, router]); + }, [installation, isRegister, router]); + + const onSubmit: SubmitHandler<FormData> = async data => { + try { + const response = await fetch(`${API_SERVER_URL}/register/password`, {
would be nice if we can wrap the api call using react query (check out `api.ts` file)
hyperdx
github_2023
typescript
81
hyperdxio
wrn14897
@@ -9,27 +10,89 @@ import LandingHeader from './LandingHeader'; import * as config from './config'; import api from './api'; +type FormData = { + email: string; + password: string; +}; + export default function AuthPage({ action }: { action: 'register' | 'login' }) { + const isRegister = action === 'register'; + const { + register, + handleSubmit, + formState: { errors, isSubmitting }, + setError, + } = useForm<FormData>({ + reValidateMode: 'onSubmit', + }); const router = useRouter(); const { err, msg } = router.query; const { data: installation } = api.useInstallation(); const verificationSent = msg === 'verify'; - const title = `HyperDX - ${action === 'register' ? 'Sign up' : 'Login'}`; + const title = `HyperDX - ${isRegister ? 'Sign up' : 'Login'}`; useEffect(() => { // If an OSS user accidentally lands on /register after already creating a team // redirect them to login instead - if ( - config.IS_OSS && - installation?.isTeamExisting === true && - action === 'register' - ) { + if (config.IS_OSS && installation?.isTeamExisting === true && isRegister) { router.push('/login'); } - }, [installation, action, router]); + }, [installation, isRegister, router]); + + const onSubmit: SubmitHandler<FormData> = async data => { + try { + const response = await fetch(`${API_SERVER_URL}/register/password`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(data), + }); + const jsonData = await response.json(); + + if (response.ok) { + return router.push('/search'); + } + + if (Array.isArray(jsonData) && jsonData[0]?.errors?.issues) { + return jsonData[0].errors.issues.forEach((issue: any) => { + setError(issue.path[0], {
👍
hyperdx
github_2023
typescript
81
hyperdxio
wrn14897
@@ -90,10 +134,17 @@ export default function AuthPage({ action }: { action: 'register' | 'login' }) { <Form.Control data-test-id="form-password" id="password" - name="password" type="password" className="border-0" + {...form.password}
nit: not super critical. I think it would be nice to add 'confirm password' field and the icon to toggle 'show password'
hyperdx
github_2023
typescript
82
hyperdxio
MikeShi42
@@ -1648,6 +1660,24 @@ function PropertySubpanel({ </Button> </Link> ) : null} + + {!!toggleColumn && keyPath.length === 1 ? ( + <Button + className="fs-8 text-muted-hover child-hover-trigger p-0" + variant="link" + as="a" + title={`${ + displayedColumns?.includes(keyPathString) + ? 'Remove' + : 'Add' + } ${keyPathString} column`}
```suggestion } ${keyPathString} column from results table`} ``` Nit: Would make it a tiny bit more clear what the button does, though the table icon should help!
hyperdx
github_2023
typescript
77
hyperdxio
wrn14897
@@ -663,78 +684,100 @@ export const getMetricsChart = async ({ : 'name AS group', ]; - switch (dataType) { - case 'Gauge': - selectClause.push( - aggFn === AggFn.Count - ? 'COUNT(value) as data' - : aggFn === AggFn.Sum - ? `SUM(value) as data` - : aggFn === AggFn.Avg - ? `AVG(value) as data` - : aggFn === AggFn.Max - ? `MAX(value) as data` - : aggFn === AggFn.Min - ? `MIN(value) as data` - : `quantile(${ - aggFn === AggFn.P50 - ? '0.5' - : aggFn === AggFn.P90 - ? '0.90' - : aggFn === AggFn.P95 - ? '0.95' - : '0.99' - })(value) as data`, - ); - break; - case 'Sum': - selectClause.push( - aggFn === AggFn.Count - ? 'COUNT(delta) as data' - : aggFn === AggFn.Sum - ? `SUM(delta) as data` - : aggFn === AggFn.Avg - ? `AVG(delta) as data` - : aggFn === AggFn.Max - ? `MAX(delta) as data` - : aggFn === AggFn.Min - ? `MIN(delta) as data` - : `quantile(${ - aggFn === AggFn.P50 - ? '0.5' - : aggFn === AggFn.P90 - ? '0.90' - : aggFn === AggFn.P95 - ? '0.95' - : '0.99' - })(delta) as data`, - ); - break; - default: - logger.error(`Unsupported data type: ${dataType}`); - break; + const isRate = isRateAggFn(aggFn); + + if (dataType === 'Gauge' || dataType === 'Sum') { + selectClause.push( + aggFn === AggFn.Count + ? 'COUNT(value) as data' + : aggFn === AggFn.Sum + ? `SUM(value) as data` + : aggFn === AggFn.Avg + ? `AVG(value) as data` + : aggFn === AggFn.Max + ? `MAX(value) as data` + : aggFn === AggFn.Min + ? `MIN(value) as data` + : aggFn === AggFn.SumRate + ? `SUM(rate) as data` + : aggFn === AggFn.AvgRate + ? `AVG(rate) as data` + : aggFn === AggFn.MaxRate + ? `MAX(rate) as data` + : aggFn === AggFn.MinRate + ? `MIN(rate) as data` + : `quantile(${ + aggFn === AggFn.P50 || aggFn === AggFn.P50Rate + ? '0.5' + : aggFn === AggFn.P90 || aggFn === AggFn.P90Rate + ? '0.90' + : aggFn === AggFn.P95 || aggFn === AggFn.P95Rate + ? '0.95' + : '0.99' + })(${isRate ? 'rate' : 'value'}) as data`, + ); + } else { + logger.error(`Unsupported data type: ${dataType}`); } + const rateMetricSource = SqlString.format( + ` +SELECT + if( + runningDifference(value) < 0 + OR neighbor(_string_attributes, -1, _string_attributes) != _string_attributes,
I assume this handles the edge cases. I wonder if this map comparison is strict enough or we need to sort keys first
hyperdx
github_2023
typescript
77
hyperdxio
wrn14897
@@ -663,78 +684,100 @@ export const getMetricsChart = async ({ : 'name AS group', ]; - switch (dataType) { - case 'Gauge': - selectClause.push( - aggFn === AggFn.Count - ? 'COUNT(value) as data' - : aggFn === AggFn.Sum - ? `SUM(value) as data` - : aggFn === AggFn.Avg - ? `AVG(value) as data` - : aggFn === AggFn.Max - ? `MAX(value) as data` - : aggFn === AggFn.Min - ? `MIN(value) as data` - : `quantile(${ - aggFn === AggFn.P50 - ? '0.5' - : aggFn === AggFn.P90 - ? '0.90' - : aggFn === AggFn.P95 - ? '0.95' - : '0.99' - })(value) as data`, - ); - break; - case 'Sum': - selectClause.push( - aggFn === AggFn.Count - ? 'COUNT(delta) as data' - : aggFn === AggFn.Sum - ? `SUM(delta) as data` - : aggFn === AggFn.Avg - ? `AVG(delta) as data` - : aggFn === AggFn.Max - ? `MAX(delta) as data` - : aggFn === AggFn.Min - ? `MIN(delta) as data` - : `quantile(${ - aggFn === AggFn.P50 - ? '0.5' - : aggFn === AggFn.P90 - ? '0.90' - : aggFn === AggFn.P95 - ? '0.95' - : '0.99' - })(delta) as data`, - ); - break; - default: - logger.error(`Unsupported data type: ${dataType}`); - break; + const isRate = isRateAggFn(aggFn); + + if (dataType === 'Gauge' || dataType === 'Sum') { + selectClause.push( + aggFn === AggFn.Count + ? 'COUNT(value) as data' + : aggFn === AggFn.Sum + ? `SUM(value) as data` + : aggFn === AggFn.Avg + ? `AVG(value) as data` + : aggFn === AggFn.Max + ? `MAX(value) as data` + : aggFn === AggFn.Min + ? `MIN(value) as data` + : aggFn === AggFn.SumRate + ? `SUM(rate) as data` + : aggFn === AggFn.AvgRate + ? `AVG(rate) as data` + : aggFn === AggFn.MaxRate + ? `MAX(rate) as data` + : aggFn === AggFn.MinRate + ? `MIN(rate) as data` + : `quantile(${ + aggFn === AggFn.P50 || aggFn === AggFn.P50Rate + ? '0.5' + : aggFn === AggFn.P90 || aggFn === AggFn.P90Rate + ? '0.90' + : aggFn === AggFn.P95 || aggFn === AggFn.P95Rate + ? '0.95' + : '0.99' + })(${isRate ? 'rate' : 'value'}) as data`, + ); + } else { + logger.error(`Unsupported data type: ${dataType}`); } + const rateMetricSource = SqlString.format( + ` +SELECT + if( + runningDifference(value) < 0 + OR neighbor(_string_attributes, -1, _string_attributes) != _string_attributes, + nan, + runningDifference(value) + ) AS rate, + ts_bucket as timestamp, + _string_attributes, + min_name as name +FROM + ( + SELECT + toStartOfInterval(timestamp, INTERVAL ?) as ts_bucket, + min(value) as value, + _string_attributes, + min(name) as min_name + FROM + ?? + WHERE + name = ? + AND data_type = ? + AND (?) + GROUP BY + _string_attributes,
can we also group by the `name` here ?
hyperdx
github_2023
others
66
hyperdxio
MikeShi42
@@ -185,6 +185,15 @@ comprehensive documentation on how we balance between cloud-only and open source features in the future. In the meantime, we're highly aligned with Gitlab's [stewardship model](https://handbook.gitlab.com/handbook/company/stewardship/). +## Frequently Asked Questions
Just throwing this out there - we should probably have a separate deployment guide to wrap up some of the new stuff around custom URLs, log levels, etc. that we get from users that need to customize their deployment beyond a local stack. And help keep the readme lean to mainly for quick start + project overview. Not something we need to do this minute.
hyperdx
github_2023
others
66
hyperdxio
MikeShi42
@@ -185,6 +185,15 @@ comprehensive documentation on how we balance between cloud-only and open source features in the future. In the meantime, we're highly aligned with Gitlab's [stewardship model](https://handbook.gitlab.com/handbook/company/stewardship/). +## Frequently Asked Questions + +#### How to suppress all logs from HyperDX itself ? + +To suppress logs of a service, you can comment out the `HYPERDX_API_KEY` +environment variable in the docker-compose.yml file. Logs mainly come from
> Logs mainly come from `app`, `api` and `miner` services. I'm not sure if this blanket statement is true, I think otel collector and vector are even more spammy and probably the thing I'd want to tune with log level the most. I think we can just omit this line for now since users can likely find which log source they're interested in muting anyways if they find it spammy.
hyperdx
github_2023
typescript
45
hyperdxio
MikeShi42
@@ -435,14 +458,36 @@ export const RawLogTable = memo( fetchMoreOnBottomReached(tableContainerRef.current); }, [fetchMoreOnBottomReached]); - const table = useReactTable({ - data: dedupLogs, - columns, - getCoreRowModel: getCoreRowModel(), - // debugTable: true, - enableColumnResizing: true, - columnResizeMode: 'onChange', - }); + //TODO: fix any + const onColumnSizingChange = (updaterOrValue: any) => { + const state = + updaterOrValue instanceof Function ? updaterOrValue() : updaterOrValue; + setColumnSizeStorage({ ...columnSizeStorage, ...state }); + }; + + const reactTableProps = (): TableOptions<any> => {
I think it might be good to memo this value right?
hyperdx
github_2023
typescript
45
hyperdxio
MikeShi42
@@ -377,7 +390,7 @@ export const RawLogTable = memo( {info.getValue<string>()} </span> ), - size: 150, + size: columnSizeStorage[column] ?? 150,
I saw that the linter wasn't happy about this missing from the dep array which I'd like to have fixed, but noticed that when added the resizing no longer worked. The side-effect of this as it is today is if you hit reset column widths, it doesn't actually reset column widths until the page is refreshed which is a pretty odd experience. I'm wondering if you have any ideas on how to workaround those problems?
hyperdx
github_2023
typescript
45
hyperdxio
MikeShi42
@@ -396,6 +409,16 @@ export const RawLogTable = memo( </span> </span> )} + <span>
I was thinking that the reset should live as a reset icon next to the gear icon on the top right of the table so it won't be too much visual clutter. Additionally I'd love to see it only when the table has column persistence enabled (with a `tableId` and also only if there's actually resized columns. Was thinking something like this where the `bi-gear-fill` icon is currently: ```jsx {headerIndex === headerGroup.headers.length - 1 && ( <div className="d-flex align-items-center" style={{ position: 'absolute', right: 8, top: 0, bottom: 0, }} > {tableId != null && Object.keys(columnSizeStorage).length > 0 && ( <div className="fs-8 text-muted-hover" role="button" onClick={() => setColumnSizeStorage({})} title="Reset Column Widths" > <i className="bi bi-arrow-clockwise" /> </div> )} {onSettingsClick != null && ( <div className="fs-8 text-muted-hover ms-2" role="button" onClick={() => onSettingsClick()} > <i className="bi bi-gear-fill" /> </div> )} </div> )} ```
hyperdx
github_2023
typescript
38
hyperdxio
wrn14897
@@ -1,6 +1,6 @@ import * as fns from 'date-fns'; import SqlString from 'sqlstring'; -import _ from 'lodash'; +import map from 'lodash/map';
I think we don't need to do the tree shaking for files in `api/`.
hyperdx
github_2023
typescript
38
hyperdxio
wrn14897
@@ -1,18 +1,14 @@ -import _ from 'lodash'; +import { getWinsonTransport } from '@hyperdx/node-opentelemetry'; import expressWinston from 'express-winston'; import winston, { addColors } from 'winston'; -import { getWinsonTransport } from '@hyperdx/node-opentelemetry'; import { APP_TYPE, HYPERDX_API_KEY, INGESTOR_API_URL, - IS_DEV, IS_PROD, } from '../config'; -import type { IUser } from '../models/user';
👍
hyperdx
github_2023
typescript
28
hyperdxio
MikeShi42
@@ -13,6 +13,7 @@ import cx from 'classnames'; import { Button, Modal } from 'react-bootstrap'; import stripAnsi from 'strip-ansi'; import { CSVLink } from 'react-csv'; +import { curry } from 'lodash';
optional nit: we don't have any tree-shaking for lodash built in the build chain so it'd be preferable to do `import curry from lodash/curry`. However, we already import all of lodash in a few other components and it needs to be made consistent across the entire code base. We can merge this as-is, since we're already inconsistent, and I made a follow-up issue addressing the broader issue in our code base https://github.com/hyperdxio/hyperdx/issues/36
hyperdx
github_2023
typescript
33
hyperdxio
MikeShi42
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react'; import { useHotkeys } from 'react-hotkeys-hook'; import { Replayer } from 'rrweb'; import { throttle } from 'lodash'; +import cn from 'classnames';
```suggestion import cx from 'classnames'; ``` Just a nit - we import `classnames` as `cx` (tl;dr due to my time at fb...) - would be awesome to have this import aligned with that as well.
hyperdx
github_2023
typescript
9
hyperdxio
wrn14897
@@ -1090,9 +1089,36 @@ export const getSessions = async ({ ], ); + const sessionsWithRecordingsQuery = SqlString.format( + `WITH sessions AS (${sessionsWithSearchQuery}),
nit: would be nice to merge queries for readablility (also make query parameterization migration a bit easier). but no big deal, I can clean it up later
hyperdx
github_2023
typescript
721
hyperdxio
teeohhem
@@ -511,7 +511,7 @@ export const MemoChart = memo(function MemoChart({ <Tooltip content={<HDXLineChartTooltip numberFormat={numberFormat} />} wrapperStyle={{ - zIndex: 1000, + zIndex: 0.1,
Seems like a good change, but I wonder why the 1000 value was there to begin with. We can merge and find out later :)
hyperdx
github_2023
typescript
719
hyperdxio
dhable
@@ -259,7 +260,7 @@ export const InfraPodsStatusTable = ({ row["arrayElement(ResourceAttributes, 'k8s.namespace.name')"], node: row["arrayElement(ResourceAttributes, 'k8s.node.name')"], restarts: row['last_value(k8s.container.restarts)'], - uptime: row['sum(k8s.pod.uptime)'], + uptime: row['undefined(k8s.pod.uptime)'],
It does look strange expressed like that but probably good enough for now. Maybe we need to alias something like `any` to mean undefined in the string?
wolverine
github_2023
typescript
33
biobootloader
nervousapps
@@ -0,0 +1,141 @@ +import { + ExtensionContext, + workspace, + Position, + TextEditor, + Range, + commands, + window +} from 'vscode'; +import axios from 'axios'; +import { ChatCompletionRequestMessage } from 'openai'; + +let openaikey = ''; + +// Returns a promise when stream ends. Procs onDataFunction on every data event. +// See https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events +// Responsiblity of caller to register event listener. +const streamCompletion = async (prompt: string, onDataFunction: (chunk: any) => void): Promise<void> => { + const messages: ChatCompletionRequestMessage[] = [ + { role: 'user', content: prompt } + ]; + const headers = { + ['Content-Type']: 'application/json', + ['Authorization']: `Bearer ${openaikey}`, + }; + + const configurationModel = await workspace.getConfiguration().get('wolverine.model'); + const data = { + 'model': configurationModel || 'gpt-3.5-turbo', + 'messages': messages, + 'temperature': 0.9, + 'stream': true, + }; + return new Promise(async (resolve) => { + const response = await axios({ + method: 'post', + url: 'https://api.openai.com/v1/chat/completions', + headers: headers, + data: data, + responseType: 'stream', + }); + response.data.on('data', onDataFunction); + response.data.on('end', () => { + resolve(); + }); + }); +}; + +const countCharacters = (text: string) => text.replace(/\n/g, '').length; +const countNewLines = (text: string) => text.match(/\n/g)?.length || 0; +const getNewCursorLocation = (textStream: string, currentLine: number, currentCharacter: number): { newCharacterLocation: number, newLineLocation: number } => { + const numberOfNewLines = countNewLines(textStream); + const newCharacterLocation = numberOfNewLines === 0 ? countCharacters(textStream) + currentCharacter : 0; + const newLineLocation = numberOfNewLines + currentLine; + return { newCharacterLocation, newLineLocation }; +}; + +const deleteRange = async (activeEditor: TextEditor, range: Range) => { + await activeEditor.edit(editBuilder => { + editBuilder.delete(range); + }); +}; + +// Yacine threw most of the complexity into here. +// Holds a buffer in a javascript array, registers a event listener on a server-sent events function, builds the buffer +// Takes a position, and flushes the buffer on a preconfigured cron into the provided cursor position. +const useBufferToUpdateTextContentsWhileStreamingOpenAIResponse = async (activeEditor: TextEditor, position: Position, prompt: string) => { + let currentCharacter = position.character; + let currentLine = position.line; + let buffer: string[] = []; + let doneStreaming = false; + const onDataFunction = (word: any) => { + const newContent = word.toString().split('data: ') + .map((line: string) => line.trim()) + .filter((line: string) => line.length > 0) + .map((line: string) => JSON.parse(line).choices[0].delta.content); + buffer = [...buffer, ...newContent]; + }; + streamCompletion(prompt, onDataFunction).then(() => doneStreaming = true); + while (!doneStreaming || buffer.length >= 0) { + const word: string | undefined = buffer.shift(); + if (word) { + let { newCharacterLocation, newLineLocation } = getNewCursorLocation(word, currentLine, currentCharacter); + const position = new Position(currentLine, currentCharacter); + await activeEditor.edit((editBuilder) => { + editBuilder.insert(position, word); + }); + currentCharacter = newCharacterLocation; + currentLine = newLineLocation; + } + // TODO I should make this buffer flush configurable. + await sleep(30); + } +}; + +const constructPrompt = async (text: string): Promise<string> => { + const defaultPrompt = ` +INSTRUCTIONS: +The following text provided has come straight from my text editor. I have an extension that can send my text output to you, often. +I've added my instructions in the comments, please attend to the comments, and output the code. +When you output the code, please don't add any human english language. Your entire output must not cause any errors! +Output code that effectively does the same thing of what I sent you, my extension replaces the text that I've highlighted and sent. +Remember, you'll have to send me any messages in comments! +CODE: +`; + const configuredPrompt = await workspace.getConfiguration().get('wolverine.prompt'); + return (configuredPrompt || defaultPrompt) + text; +}; + +export async function activate(context: ExtensionContext) { + + let disposable = commands.registerCommand('wolverine.directedHeal', async () => { + // Forgive me father.. + openaikey = await workspace.getConfiguration().get('wolverine.UNSAFE.OpenaiApiKeySetting') || '';
Hi, in this extension for example [codeGPT](https://github.com/davila7/code-gpt-docs), you can give the key with a user prompt. I don't know how it is stored but it is not hardcoded in a configfile :)
wolverine
github_2023
python
16
biobootloader
biobootloader
@@ -109,7 +109,9 @@ def send_error_to_gpt(file_path, args, error_message, model=DEFAULT_MODEL): return json_validated_response(model, messages) -def apply_changes(file_path, changes: list): +# Added the flag -confirm which will ask user before writing changes to file +
```suggestion ```
wolverine
github_2023
python
22
biobootloader
biobootloader
@@ -114,7 +124,7 @@ def apply_changes(file_path, changes_json): print(line, end="") -def main(script_name, *script_args, revert=False, model="gpt-4"): +def main(script_name, *script_args, revert=False, model="gpt-3.5-turbo"):
please keep the default as gpt-4
wolverine
github_2023
others
13
biobootloader
biobootloader
@@ -4,10 +4,13 @@ Because you are part of an automated system, the format you respond in is very s In addition to the changes, please also provide short explanations of the what went wrong. A single explanation is required, but if you think it's helpful, feel free to provide more explanations for groups of more complicated changes. Be careful to use proper indentation and spacing in your changes. An example response could be: +Be ABSOLUTELY SURE to include the CORRECT INDENTATION when making replacements. + +example response: [ {"explanation": "this is just an example, this would usually be a brief explanation of what went wrong"}, {"operation": "InsertAfter", "line": 10, "content": "x = 1\ny = 2\nz = x * y"}, {"operation": "Delete", "line": 15, "content": ""}, - {"operation": "Replace", "line": 18, "content": "x += 1"}, + {"operation": "Replace", "line": 18, "content": " x += 1"},
Nice! Any idea how much better this makes it at indentation errors?
wolverine
github_2023
python
13
biobootloader
biobootloader
@@ -25,7 +33,41 @@ def run_script(script_name, script_args): return result.decode("utf-8"), 0 -def send_error_to_gpt(file_path, args, error_message, model): +def send_error_to_gpt(file_path, args, error_message, model=DEFAULT_MODEL): + def json_validated_response(model, messages):
nice idea, I saw 3.5-turbo especially had issues with this. Can you extract `json_validated_response` to be a standalone function? Seems a bit long to be an inner function
wolverine
github_2023
others
12
biobootloader
biobootloader
@@ -0,0 +1 @@ +OPENAI_API_KEY=your_api_key
```suggestion OPENAI_API_KEY=your_api_key ```
wolverine
github_2023
others
12
biobootloader
biobootloader
@@ -1,2 +1,4 @@ venv openai_key.txt
```suggestion ```
wolverine
github_2023
others
12
biobootloader
biobootloader
@@ -1,2 +1,4 @@ venv openai_key.txt +.venv +.env
```suggestion .env ```
wolverine
github_2023
python
8
biobootloader
biobootloader
@@ -1,3 +1,4 @@ +import argparse
```suggestion ```
AugmentOS
github_2023
python
132
AugmentOS-Community
nic-olo
@@ -0,0 +1,223 @@ +# custom +from collections import defaultdict +from agents.agent_utils import format_list_data + +# langchain +from langchain.prompts import PromptTemplate +from langchain.schema import ( + HumanMessage +) +from langchain.output_parsers import PydanticOutputParser +from langchain.schema import OutputParserException +from pydantic import BaseModel, Field +from helpers.time_function_decorator import time_function + +#pinyin +from pypinyin import pinyin, Style + +from Modules.LangchainSetup import * + +#draft word suggestion upgrade prompt by Susanna +ll_word_suggest_upgrade_agent_prompt_blueprint=""" +You are listening to a user's conversation right now. You help the language learner user by suggesting "Upgrades", contextually relevant but different words or phrases from existing vocabulary/words context in the conversation transcript (Input Text), which the user might use during the current conversation. You output 1 words in both the input language and the output language. +The system will take in the context of what is being discussed, where the user is, what’s happening around them, what the user’s goal is, etc. in order to suggest some words to them that they otherwise would not use. +Don't pick words already in the conversation! Never suggest words in Input Text! Give an upgrade word (more advanced and related synonym, idiom, or rare word) +Words should be chosen based on the fluency of the user, and which words they often use. If a user often uses a word, it should not be suggested as an Upgrade. The best Upgrades are words that the user has seen before (in their studies) but hasn’t used yet (or doesn’t use regularly) which will help them learn to use that word in the real world. + +If the learner's fluency level is less than 50, they will need Upgrades that are less advanced, a synonyms of one word from the Input Text(people use in daily life but are not used by learner). +If fluency level is 50-75 fluency level might suggest more advanced Upgrades (people do not use in Input Language, exclusively exist in Output Language in a unique way, like idiom/ culturally relevant phrases). +If fluency level is >75, only suggest Upgrades that are very rare words that appears in studies/ researches/ academic contexts/ ancient language that neither Input language user nor Output Language user use in ordinary lives. + +Input Text Language: {transcribe_language} +Output (translated) Language: {output_language} +Fluency Level: {fluency_level} + +Process: +0. Consider the fluency level of the user, which is {fluency_level}, where 0<=fluency_level<=100, with 0 being complete beginner, 50 being conversational, 75 intermediate and 100 being native speaker. +1. Skim through the Input Text and come up with a new but conversation-relevant word to someone with a fluency level of {fluency_level} AND that have not been said in the conversation. +2. Consider how common a word is (the word frequency percentile) to determine how likely the user knows that word. +3. For the upgrade word, provide in both {transcribe_language} and {output_language}. Make them short. Use context from the conversation to inform translation of homonyms. +4. Output response using the format instructions below, provide words in the order they appear in the text. Don't suggest any Upgrade that are in the "Recently Suggested" list of words. + + +Examples: + +Conversation 1: 'I ran for the train, but the fruit stand was in the way' +Input Language 1: English +Output Language 1: Chinese +Output 1: {{"upgrade": "gáo tiě","meaning": "high-speed rail"}} + +Conversation 2: "О, так вы студент биологии, это здорово" +Input Language 2: Russian +Output Language 2: English +Output 2: {{"upgrade":"botany","meaning": "the scientific study of plants"}} + +Conversation 3: "let's go and say hello to her" +Input Language 3: English +Output Language 3: Spanish +Output 3: {{"upgrade":"saludar", "meaning": "to greet"}} + +Input Text: `{conversation_context}` + +Frequency Ranking: The frequency percentile of each word tells you how common it is in daily speech (~0.1 is very common, >1.2 is rare, >13.5 is very rare). The frequency ranking of the words in the "Input Text" are: `{word_rank}` + +Recently Suggested: `{live_upgrade_word_history}` + +Output Format: {format_instructions} + +Don't output punctuation or periods! Output all lowercase! Define 1/5 of the words in the input text (never define all of the words in the input, never define highly common words like "the", "a", "it", etc.). Now provide the output: +""" + +#opposite language (either {source_language} or {target_language}, whatever is + +#This level influences the selection of upgrade word: +# - 0-49 (Beginner): suggest Upgrade word that is less advanced, meaning percentile rank >0.15 (people use in daily life but are not used by learner). +# - 50-74 (Conversational): suggest more advanced Upgrade, meaning percentile rank >1.5 (people do not use in Input Language, exclusively exists in Output Language in a unique way, like idiom/ culturally relevant phrases). +# - 75-100 (Intermediate): only suggest Upgrade that is very rare words, meaning percentile rank >30, which appears in studies/ researches/ academic contexts/ ancient language that neither Input language user nor Output Language user use in ordinary lives. + +#A word with frequency percentile 1.5 is a little uncommon, a word with percentile 0.15 is very common, a word with percentile >=30 is super rare. Use the percentile to determine words that the user might not know, where higer number is more rare. + +#*** Never do intralanguage translation (don't translate within the same language). +# using the format instructions above: +# +#There should be 1 words per run in the dict. Don't output any explanation or extra data, just this simple info. It's OK to output zero words if there are no appopriately rare words in the input text. + +#Don't suggest stop words or super common words like "yes", "no", "he", "hers", "to", "from", "thank you", "please", etc. in ANY language, but you can define even semi-common words like "exactly", "bridge", "computer", etc. for beginners with a fluency level less than 50 (current user fluency is {fluency_level}. + +#Don't pick words already in the conversation! Never suggest words in Input Text! Give an upgrade word (more advanced and related synonym, idiom, or rare word) + +#Conversation 4: "that museum’s architecture is very beautiful." +#Source Language 4: English +#Target Language 4: Chinese (Pinyin) +#Output 4: {{ "upgrade": "gǔdài","meaning": "ancient"}} + + +#Preface Rule: +#Use Pinyin when writing Chinese. Never use Chinese characters, use Pinyin. +#, use Pinyin if writing Chinese) +#3.a. If writing Chinese, output exclusively in Pinyin, avoiding Chinese characters entirely. +#NEVER OUTPUT CHINESE CHARACTERS. USE PINYIN, USE THE LATIN ALPHABET PINYIN FOR CHINESE. + +#Use Pinyin when writing Chinese. Never use Chinese characters, use Pinyin. + +# in_upgrade_translation must be in Pinyin or Latin characters. + +# If writing Chinese, output exclusively in Pinyin, avoiding Chinese characters entirely.
There's a lot of extra comment that I assume come from the original ll file, you can remove them from here they aren't needed
AugmentOS
github_2023
java
122
AugmentOS-Community
nic-olo
@@ -7,6 +7,6 @@ public class Config { public static final String serverUrl = "https://vpmkebx0cl.execute-api.us-east-2.amazonaws.com/api"; //TOSG BOX // public static final String serverUrl = "http://192.168.7.117:8080"; - public static final Boolean useDevServer = false; - public static final String devServerUrl = "/dev"; + public static final Boolean useDevServer = true; + public static final String devServerUrl = "/dev4";
Changes to the path should not be committed.
AugmentOS
github_2023
python
122
AugmentOS-Community
nic-olo
@@ -40,7 +40,7 @@ # Prod: database_uri = "mongodb://localhost:27017" server_port = 8080 -path_modifier = "" +path_modifier = "/dev4"
Same as above.
AugmentOS
github_2023
java
121
AugmentOS-Community
nic-olo
@@ -7,6 +7,6 @@ public class Config { public static final String serverUrl = "https://vpmkebx0cl.execute-api.us-east-2.amazonaws.com/api"; //TOSG BOX // public static final String serverUrl = "http://192.168.7.117:8080"; - public static final Boolean useDevServer = false; - public static final String devServerUrl = "/dev"; + public static final Boolean useDevServer = true; + public static final String devServerUrl = "/dev4";
This should not be committed.
AugmentOS
github_2023
java
99
AugmentOS-Community
CaydenPierce
@@ -341,6 +377,46 @@ public void onFailure(int code){ } } + public void requestLocation(){ + try{ + // Get location data as JSONObject + double latitude = locationSystem.lat; + double longitude = locationSystem.lng; + + // TODO: Filter here... is it meaningfully different? + if(latitude == 0 && longitude == 0) return; + + JSONObject jsonQuery = new JSONObject(); + + jsonQuery.put("Authorization", authToken); + jsonQuery.put("deviceId", deviceId); + jsonQuery.put("lat", latitude); + jsonQuery.put("lng", longitude); + + backendServerComms.restRequest(GEOLOCATION_STREAM_ENDPOINT, jsonQuery, new VolleyJsonCallback(){ + @Override + public void onSuccess(JSONObject result){ + try { + previousLat = latitude; + previousLng = longitude; + parseConvoscopeResults(result);
why are we using the parseConvoscopeResults function to parse the result of the GEOLOCATION request? Should be fixed to be its own function
AugmentOS
github_2023
java
99
AugmentOS-Community
CaydenPierce
@@ -463,6 +539,27 @@ public String[] calculateLLStringFormatted(LinkedList<DefinedWord> definedWords) return llResults; } + public String[] calculateLLContextConvoResponseFormatted(LinkedList<ContextConvoResponse> contextConvoResponses) { + if (!clearedScreenYet) {
This logic was assuming we only had translation. Should be updated now that we have multiple features.
AugmentOS
github_2023
java
99
AugmentOS-Community
CaydenPierce
@@ -487,13 +584,22 @@ public void parseConvoscopeResults(JSONObject response) throws JSONException { if (languageLearningResults.length() != 0) { llResults = calculateLLStringFormatted(getDefinedWords()); sendRowsCard(llResults); -// sendUiUpdateSingle(String.join("\n", Arrays.copyOfRange(llResults, llResults.length, 0))); List<String> list = Arrays.stream(Arrays.copyOfRange(llResults, 0, languageLearningResults.length())).filter(Objects::nonNull).collect(Collectors.toList()); Collections.reverse(list); sendUiUpdateSingle(String.join("\n", list)); - } + // ll context convo
can leave for now but this sliding buffer should 1. fixed 2. move to it's own function so we aren't copy pasting code,
AugmentOS
github_2023
java
99
AugmentOS-Community
CaydenPierce
@@ -0,0 +1,57 @@ +package com.teamopensmartglasses.convoscope; + +import android.content.Context; +import android.content.pm.PackageManager; +import android.os.Bundle; +import android.util.Log; +import android.location.Location; +import android.location.LocationListener; +import android.location.LocationManager; +import android.widget.Toast; + +import androidx.core.app.ActivityCompat; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.IOException; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; + +public class LocationSystem { + Context context; + public double lat = 0; + public double lng = 0; + private LocationManager locationManager; + + public LocationSystem(Context context) { + this.context = context; + locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); + getUserLocation(); + } + + public void getUserLocation() { + + if (ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { + // TODO: Consider calling + // ActivityCompat#requestPermissions + // here to request the missing permissions, and then overriding + // public void onRequestPermissionsResult(int requestCode, String[] permissions, + // int[] grantResults) + // to handle the case where the user grants the permission. See the documentation + // for ActivityCompat#requestPermissions for more details. + Toast.makeText(context.getApplicationContext(), "Please enable location permissions!", Toast.LENGTH_LONG);
This is called by the service, right? So Toast won't work. Is this tested?
AugmentOS
github_2023
python
99
AugmentOS-Community
CaydenPierce
@@ -0,0 +1,106 @@ +# custom +from agents.agent_utils import format_list_data + +# langchain +from langchain.prompts import PromptTemplate +from langchain.schema import ( + HumanMessage +) +from langchain.output_parsers import PydanticOutputParser +from langchain.schema import OutputParserException +from pydantic import BaseModel, Field +from helpers.time_function_decorator import time_function + +from Modules.LangchainSetup import * + + +ll_context_convo_prompt_blueprint = """ +You are an expert language teacher fluent in Russian, Chinese, French, Spanish, German, English, and more. You are listening to a user's conversation right now. The user is learning {target_language}. You help the language learner user by asking questions about their environment.
You help them by conversing with them in the target language, not just asking questions
AugmentOS
github_2023
python
99
AugmentOS-Community
CaydenPierce
@@ -0,0 +1,106 @@ +# custom +from agents.agent_utils import format_list_data + +# langchain +from langchain.prompts import PromptTemplate +from langchain.schema import ( + HumanMessage +) +from langchain.output_parsers import PydanticOutputParser +from langchain.schema import OutputParserException +from pydantic import BaseModel, Field +from helpers.time_function_decorator import time_function + +from Modules.LangchainSetup import * + + +ll_context_convo_prompt_blueprint = """ +You are an expert language teacher fluent in Russian, Chinese, French, Spanish, German, English, and more. You are listening to a user's conversation right now. The user is learning {target_language}. You help the language learner user by asking questions about their environment. + +Leveraging environmental context for language learning can significantly enhance the educational experience. Given data about the points of interest around a user's current location, your task is to craft tailored language learning activities. These activities should be specifically designed to match the learner's proficiency level in their target language, encouraging interaction with their surroundings through the target language lens.
Needs rework, misleading and long
AugmentOS
github_2023
python
99
AugmentOS-Community
CaydenPierce
@@ -0,0 +1,106 @@ +# custom +from agents.agent_utils import format_list_data + +# langchain +from langchain.prompts import PromptTemplate +from langchain.schema import ( + HumanMessage +) +from langchain.output_parsers import PydanticOutputParser +from langchain.schema import OutputParserException +from pydantic import BaseModel, Field +from helpers.time_function_decorator import time_function + +from Modules.LangchainSetup import * + + +ll_context_convo_prompt_blueprint = """ +You are an expert language teacher fluent in Russian, Chinese, French, Spanish, German, English, and more. You are listening to a user's conversation right now. The user is learning {target_language}. You help the language learner user by asking questions about their environment. + +Leveraging environmental context for language learning can significantly enhance the educational experience. Given data about the points of interest around a user's current location, your task is to craft tailored language learning activities. These activities should be specifically designed to match the learner's proficiency level in their target language, encouraging interaction with their surroundings through the target language lens. + +Target Language: {target_language} +Fluency Level: {fluency_level} + +Process: +0. Consider the fluency level of the user, which is {fluency_level}, where 0<=fluency_level<=100, with 0 being complete beginner, 50 being conversational, 75 intermediate and 100 being native speaker. +1. Review the given locations and select the most interesting ones as the basis for your questions, ensuring they align with the learner's proficiency level. +The input follows the format for each location: +'name: [Location Name]; types: [type1, type2, ...]' +2. Generate questions or prompts in the target language tailored to both the learner's level and the selected locations, varying from simple vocabulary tasks for beginners to nuanced debates for native speakers.
OK for now but should update to be conversational, not just single shot
AugmentOS
github_2023
python
99
AugmentOS-Community
CaydenPierce
@@ -286,8 +296,16 @@ async def ui_poll_handler(request, minutes=0.5): if "language_learning" in features: language_learning_results = db_handler.get_language_learning_results_for_user_device(user_id=user_id, device_id=device_id) resp["language_learning_results"] = language_learning_results - print("RETURNING THIS LANGUAGE LEARNING RESULTS") - print(language_learning_results) + if language_learning_results: + print("server.py ================================= LLRESULT") + print(language_learning_results) + + if "ll_context_convo" in features and SEND_LL_CONTEXT_CONVO_RESULTS:
Why is constant here? SHould be removed.
AugmentOS
github_2023
python
99
AugmentOS-Community
CaydenPierce
@@ -419,6 +439,39 @@ async def send_agent_chat_handler(request): return web.Response(text=json.dumps({'success': True, 'message': "Got your message: {}".format(chat_message)}), status=200) + +async def update_gps_location_for_user(request): + body = await request.json() + + id_token = body.get('Authorization') + user_id = await verify_id_token(id_token) + device_id = body.get('deviceId') + + if user_id is None: + raise web.HTTPUnauthorized() + + location = dict() + location['lat'] = body.get('lat') + location['lng'] = body.get('lng') + + # 400 if missing params + if not user_id: + print("user_id none in update_gps_location_for_user, exiting with error response 400.") + return web.Response(text='no userId in request', status=400) + if not location['lat'] or not location['lng']: + print("location none in update_gps_location_for_user, exiting with error response 400.") + return web.Response(text='no chatMessage in request', status=400) + + # print("SEND UPDATE LOCATION FOR USER_ID: " + user_id) + db_handler.add_gps_location_for_user(user_id, location) + + locations = db_handler.get_gps_location_results_for_user_device(user_id, device_id) + if len(locations) > 1: + print("difference in locations: ", locations[-1]['lat'] - locations[-2]['lat'], locations[-1]['lng'] - locations[-2]['lng']) + + return web.Response(text=json.dumps({'success': True, 'message': "Got your location: {}".format(location)}), status=200) + + async def rate_result_handler(request):
what is this?
AugmentOS
github_2023
python
99
AugmentOS-Community
CaydenPierce
@@ -494,18 +554,18 @@ async def protected_route(request): app.add_routes( [ web.get('/protected', protected_route), + web.get('/image', return_image_handler), web.post('/chat', chat_handler), web.post('/button_event', button_handler), web.post('/ui_poll', ui_poll_handler), web.post('/upload_userdata', upload_user_data_handler), - web.get('/image', return_image_handler), web.post('/run_single_agent', run_single_expert_agent_handler), web.post('/send_agent_chat', send_agent_chat_handler), web.post('/rate_result', rate_result_handler), web.post('/start_recording', start_recording_handler), web.post('/save_recording', save_recording_handler), web.post('/load_recording', load_recording_handler), - web.post('/set_user_settings', set_user_settings)
should not be removed
AugmentOS
github_2023
python
107
AugmentOS-Community
nic-olo
@@ -22,21 +22,26 @@ def load_frequency_list(language_code: str) -> pd.DataFrame: # Construct the path to the frequency list folder_name = language_code_map[language_code] - file_path = os.path.join("./word_frequency_lists/content/2018", folder_name, f"{folder_name}_50k.txt") + file_path = os.path.join("./word_frequency_lists/content/2018", folder_name, f"{folder_name}_{type}.txt") # Load the frequency list into a DataFrame df = pd.read_csv(file_path, sep=" ", names=['word', 'frequency'], header=None) df['rank'] = df['frequency'].rank(ascending=False) return df def get_word_frequency_percentiles(transcript: str, language_code: str) -> dict: - df = load_frequency_list(language_code) + df = load_frequency_list(language_code, '50k') words_dict = pd.Series(df['rank'].values,index=df['word']).to_dict() total_words = len(df) # Get the total number of words in the dataset + df = load_frequency_list(language_code, 'full')
50k will have us covered 99% of the time. Therefore, I suggest you only load up the full frequency list as a last resort, i.e. after you can't find a word.
AugmentOS
github_2023
others
96
AugmentOS-Community
reeceyang
@@ -37,10 +40,9 @@ "@types/regenerator-runtime": "^0.13.1", "@typescript-eslint/eslint-plugin": "^6.0.0", "@typescript-eslint/parser": "^6.0.0", - "@vitejs/plugin-react-swc": "^3.3.2", + "@vitejs/plugin-react": "^4.2.1",
I think we were using SWC for faster builds, are you able to get it to work using SWC?
AugmentOS
github_2023
typescript
61
AugmentOS-Community
nic-olo
@@ -1,14 +1,12 @@ import { useEffect } from "react"; import "./index.css"; -import { useTranscription } from "./hooks/useTranscription"; -import { useUiUpdateBackendPoll } from "./hooks/useUiUpdateBackendPoll"; import { generateRandomUserId, setUserIdAndDeviceId } from "./utils/utils"; import Cookies from "js-cookie"; -import MainLayout from "./layouts/MainLayout"; +import StudyLayout from "./layouts/StudyLayout"; +import { useTrackTabChange } from "./hooks/useTrackTabChange"; export default function App() { - useTranscription(); - useUiUpdateBackendPoll(); + useTrackTabChange();
Could you use a variable to disable the backend bits instead of hardcoding the changes please?
AugmentOS
github_2023
python
34
AugmentOS-Community
KenjiPcx
@@ -169,10 +194,18 @@ def get_all_transcripts_for_user(self, user_id, delete_after=False): def combine_text_from_transcripts(self, transcripts, recent_transcripts_only=True): curr_time = time.time() + last_index = len(transcripts) - 1 text = "" - for t in transcripts: + + for index, t in enumerate(transcripts): if recent_transcripts_only and (curr_time - t['timestamp'] < self.final_transcript_validity_time): - text += t['text'] + " " + text += t['text']
this and the condition below could technically be combined into a line, also does this text += t['text'] account for a space between each transcript t?
AugmentOS
github_2023
python
34
AugmentOS-Community
KenjiPcx
@@ -202,7 +234,7 @@ def get_new_cse_transcripts_for_user(self, user_id, delete_after=False): backslide_words = ' '.join(backslide_word_list[-(self.backslide-len(backslide_word_list)):]) words_from_start = first_transcript['text'][start_index:].strip() - first_transcript['text'] = backslide_words + " " + words_from_start + first_transcript['text'] = backslide_words + " " + words_from_start if words_from_start else backslide_words
didn't know python would parse "" as false and "123" as true, not really glaring but could be more explicit to improve readability
AugmentOS
github_2023
python
34
AugmentOS-Community
KenjiPcx
@@ -20,7 +20,7 @@ <Transcript start>{conversation_context}<Transcript end> [Your Task] -Now use your tools and knowledge to answer the query to the best of your ability. The question or request you are to answer is the last (final) question/request posed by the human to you in the below 'Query'. Make your answer as concise and succinct as possible. Leave out filler words and redundancy to make the answer high entropy and as to-the-point as possible. Never answer with more than 240 characters, and try to make it even less than that. Most answers can be given in under 10 words. +Now use your knowledge and/or tools (if needed) to answer the query to the best of your ability. Do not use your tools if you already know the answer to the query. The query may accidentally contain some extra speech at the end, you should ignore any noise and try to find the user's inteded query. Make your answer as concise and succinct as possible. Leave out filler words and redundancy to make the answer high entropy and as to-the-point as possible. Never answer with more than 240 characters, and try to make it even less than that. Most answers can be given in under 10 words.
line 38 below, I was wondering if we could move the new_expert_agent out of the function and define it somewhere in the file instead, I think it is fine to reuse the same generic agent instead of creating one everytime the explicit agent is called
AugmentOS
github_2023
python
34
AugmentOS-Community
KenjiPcx
@@ -39,11 +39,13 @@ def explicit_query_processing_loop(): if current_time > last_wake_word_time + force_query_time: is_query_ready = True - # If there has been a pause - elif (len(user['final_transcripts']) != 0) and (current_time > user['final_transcripts'][-1]['timestamp'] + pause_query_time): + # If there has been a pause (the latest transcript is old) + latest_transcript = dbHandler.get_latest_transcript_from_user_obj(user) + if latest_transcript and (current_time > latest_transcript['timestamp'] + pause_query_time): is_query_ready = True if not is_query_ready: continue +
line 85 below, where the insight gets generated, is it assumed that it would be like "Insight: this is an insight"? because in the other branch i changed insights to return a dict of { insight: str, resource_url: https://<link>, motive: str }
AugmentOS
github_2023
typescript
17
AugmentOS-Community
nic-olo
@@ -1,7 +1,8 @@ export type Entity = { - name: string; - summary: string; + name?: string;
Shouldn't the name be non-nullable?
AugmentOS
github_2023
python
16
AugmentOS-Community
nic-olo
@@ -62,6 +63,20 @@ def initCacheCollection(self): ### MISC ### + # Returns the index of the nearest beginning of a word before "currIndex" + # EX: findClosestStartWordIndex('hello world, my name is alex!', 5) => 5 + # EX: ... + # EX: findClosestStartWordIndex('hello world, my name is alex!', 11) => 5 + # EX: findClosestStartWordIndex('hello world, my name is alex!', 12) => 12 + def findClosestStartWordIndex(self, text, currIndex):
nit: use snake_case
AugmentOS
github_2023
python
16
AugmentOS-Community
nic-olo
@@ -187,32 +232,26 @@ def getNewCseTranscriptsForUser(self, userId, deleteAfter=False): self.userCollection.update_one(filter=filter, update=update) return unconsumed_transcripts + def updateCseConsumedTranscriptIdxForUser(self, userId, newIndex):
nit: use snake_case
AugmentOS
github_2023
python
16
AugmentOS-Community
nic-olo
@@ -62,6 +63,20 @@ def initCacheCollection(self): ### MISC ### + # Returns the index of the nearest beginning of a word before "currIndex"
Docstring should be a triple-quoted string beneath the function name, e.g. def func_name(self, param): """ Docstring """
AugmentOS
github_2023
python
15
AugmentOS-Community
nic-olo
@@ -24,40 +33,85 @@ \n Text to summarize: \n{} \nSummary (8 words or less): """ +ogPromptWithContext = """
nit: use snake_case
AugmentOS
github_2023
python
15
AugmentOS-Community
nic-olo
@@ -3,11 +3,20 @@ # OpenAI imports import openai from summarizer.sbert import SBertSummarizer -from server_config import openai_api_key +from server_config import openai_api_key, use_azure_openai, azure_openai_api_key, azure_openai_api_base, azure_openai_api_deployment openai.api_key = openai_api_key -ogPrompt = """Please summarize the following "entity description" text to 8 words or less, extracting the most important information about the entity. The summary should be easy to parse very quickly. Leave out filler words. Don't write the name of the entity. Use less than 8 words for the entire summary. Be concise, brief, and succinct. +### For use with Azure OpenAI ### +if use_azure_openai: + print("$$$ USING AZURE OPENAI $$$") + openai.api_key = azure_openai_api_key + openai.api_base = azure_openai_api_base # your endpoint should look like the following https://YOUR_RESOURCE_NAME.openai.azure.com/ + openai.api_type = 'azure' + openai.api_version = '2023-08-01-preview' # this may change in the future + deployment_name = azure_openai_api_deployment # This will correspond to the custom name you chose for your deployment when you deployed a model. + +ogPromptNoContext = """Please summarize the following "entity description" text to 8 words or less, extracting the most important information about the entity. The summary should be easy to parse very quickly. Leave out filler words. Don't write the name of the entity. Use less than 8 words for the entire summary. Be concise, brief, and succinct.
nit: use snake_case
SmartGlassesManager
github_2023
java
5
AugmentOS-Community
CaydenPierce
@@ -0,0 +1,18 @@ +package com.smartglassesmanager.androidsmartphone.supportedglasses; + +// these glasses are pretty bad. There's no home button/gesture... the text/font size is all off android specs. Arms are big. The company has zero customer support. We might drop support for these - cayden +public class Monocle extends SmartGlassesDevice { + public Monocle() { + deviceModelName = "Monocle; + deviceIconName = "Monocle"; + anySupport = true; + fullSupport = false; + glassesOs = SmartGlassesOperatingSystem.ANDROID_OS_GLASSES;
Monocle does not run Android. There is no way this PR works. As discussed on Discord, there needs to be a new SGC to support Monocle, and Monocle will need its own frontend.
tokenized-strategy
github_2023
others
98
yearn
spalen0
@@ -780,6 +780,17 @@ contract TokenizedStrategy { return _maxWithdraw(_strategyStorage(), owner); } + /** + * @notice Accepts a `maxLoss` variable in order to match the multi + * strategy vaults ABI.
```suggestion * @notice Variable `maxLoss` is ignored. * @dev Accepts a `maxLoss` variable in order to match the multi * strategy vaults ABI. ```
tokenized-strategy
github_2023
others
98
yearn
spalen0
@@ -792,6 +803,17 @@ contract TokenizedStrategy { return _maxRedeem(_strategyStorage(), owner); } + /** + * @notice Accepts a `maxLoss` variable in order to match the multi + * strategy vaults ABI.
```suggestion * @notice Variable `maxLoss` is ignored. * @dev Accepts a `maxLoss` variable in order to match the multi * strategy vaults ABI. ```
tokenized-strategy
github_2023
others
98
yearn
spalen0
@@ -497,6 +490,12 @@ contract TokenizedStrategy { ) external nonReentrant returns (uint256 shares) { // Get the storage slot for all following calls. StrategyData storage S = _strategyStorage(); + + // Deposit full balance if using max uint. + if (assets == type(uint256).max) { + assets = S.asset.balanceOf(msg.sender);
What is the use case for using `uint256.max`? I like this flow when repaying the debt but for deposit, I haven't seen it yet. Will it break the ERC4626 standard: “MUST revert if all of `assets` cannot be deposited”? https://eips.ethereum.org/EIPS/eip-4626#deposit
tokenized-strategy
github_2023
others
98
yearn
spalen0
@@ -1982,39 +2012,16 @@ contract TokenizedStrategy { * @notice Returns the domain separator used in the encoding of the signature * for {permit}, as defined by {EIP712}. * - * @dev This checks that the current chain id is the same as when the contract - * was deployed to prevent replay attacks. If false it will calculate a new - * domain separator based on the new chain id. - * * @return . The domain separator that will be used for any {permit} calls. */ function DOMAIN_SEPARATOR() public view returns (bytes32) { - StrategyData storage S = _strategyStorage(); - return - block.chainid == S.INITIAL_CHAIN_ID - ? S.INITIAL_DOMAIN_SEPARATOR - : _computeDomainSeparator(S); - } - - /** - * @dev Calculates and returns the domain separator to be used in any - * permit functions for the strategies {permit} calls. - * - * This will be used at the initialization of each new strategies storage. - * It would then be used in the future in the case of any forks in which - * the current chain id is not the same as the original. - * - */ - function _computeDomainSeparator( - StrategyData storage S - ) internal view returns (bytes32) { return keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), - keccak256(bytes(S.name)), + keccak256(bytes("Yearn Vault")), keccak256(bytes(API_VERSION)),
**Not needed but nice to do** You can store these values as constants for cheaper txs. Permit2 reference: https://github.com/Uniswap/permit2/blob/cc56ad0f3439c502c246fc5cfcc3db92bb8b7219/src/EIP712.sol#L26 Simpler version: ```solidity bytes32 internal constant _TYPE_HASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); bytes32 internal constant _NAME_HASH = keccak256("Yearn Vault"); bytes32 internal constant _VERSION_HASH = keccak256(bytes(API_VERSION)); function DOMAIN_SEPARATOR() public view returns (bytes32) { return keccak256( abi.encode( _TYPE_HASH, _NAME_HASH, _VERSION_HASH, block.chainid, address(this) ) ); } ```
tokenized-strategy
github_2023
others
103
yearn
spalen0
@@ -613,4 +613,88 @@ contract AccountingTest is Setup { assertEq(asset.balanceOf(address(yieldSource)), _amount); } + + function test_deposit_zeroAssetsPositiveSupply_reverts( + address _address, + uint256 _amount + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != address(yieldSource) + ); + + setFees(0, 0); + mintAndDepositIntoStrategy(strategy, _address, _amount); + + uint256 toLoose = _amount;
Did you mean `toLose`? The amount that will be lost -> amount to lose?
tokenized-strategy
github_2023
others
102
yearn
fp-crypto
@@ -2014,7 +2014,7 @@ contract TokenizedStrategy { keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), - keccak256(bytes(S.name)),
I really know nothing about this, but is there a reason make this an exact match against the multi-strat vaults or not?
tokenized-strategy
github_2023
others
100
yearn
fp-crypto
@@ -780,6 +780,17 @@ contract TokenizedStrategy { return _maxWithdraw(_strategyStorage(), owner); } + /** + * @notice Accepts a `maxLoss` variable in order to match the multi + * strategy vaults ABI. + */ + function maxWithdraw( + address owner,
Maybe a dumb question ... is there a reason to support strategy implementations from choosing to handle this?
tokenized-strategy
github_2023
others
99
yearn
fp-crypto
@@ -582,4 +582,29 @@ contract AccountingTest is Setup { assertEq(strategy.pricePerShare(), wad); checkStrategyTotals(strategy, 0, 0, 0, 0); } + + function test_maxUintDeposit_depositsBalance( + address _address, + uint256 _amount + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != address(yieldSource) + ); + + asset.mint(_address, _amount); + + vm.prank(_address); + asset.approve(address(strategy), _amount); + + assertEq(asset.balanceOf(_address), _amount); + + vm.prank(_address); + strategy.deposit(type(uint256).max, _address); + + // Should just deposit the available amount. + checkStrategyTotals(strategy, _amount, _amount, 0, _amount);
shouldn't this test check the users has the current amount of strategy shares?
tokenized-strategy
github_2023
others
99
yearn
fp-crypto
@@ -15,4 +15,22 @@ contract ERC4626StdTest is ERC4626Test, Setup { _vaultMayBeEmpty = true; _unlimitedAmount = true; } + + //Avoid special case for deposits of uint256 max + function test_previewDeposit( + Init memory init, + uint assets
```suggestion uint256 assets ``` Fix my feeling of ick
tokenized-strategy
github_2023
others
99
yearn
fp-crypto
@@ -15,4 +15,22 @@ contract ERC4626StdTest is ERC4626Test, Setup { _vaultMayBeEmpty = true; _unlimitedAmount = true; } + + //Avoid special case for deposits of uint256 max + function test_previewDeposit( + Init memory init, + uint assets + ) public override { + if (assets == type(uint256).max) assets -= 1; + super.test_previewDeposit(init, assets); + } + + function test_deposit( + Init memory init, + uint assets, + uint allowance
```suggestion uint256 assets, uint256 allowance ``` no ick plz
tokenized-strategy
github_2023
others
74
yearn
fp-crypto
@@ -201,7 +201,7 @@ contract TokenizedStrategy { * * Loading the corresponding storage slot for the struct does not * load any of the contents of the struct into memory. So the size - * has no effect on gas usage. + * wont increase gas usage.
```suggestion * won't increase gas usage. ```
tokenized-strategy
github_2023
others
74
yearn
fp-crypto
@@ -498,15 +502,16 @@ contract TokenizedStrategy { uint256 assets, address receiver ) external nonReentrant returns (uint256 shares) { + StrategyData storage S = _strategyStorage();
So TLDR, external/public functions load the point, internal/private functions receive the pointer?
tokenized-strategy
github_2023
others
74
yearn
fp-crypto
@@ -642,14 +677,8 @@ contract TokenizedStrategy { * @param shares The amount of the strategies shares. * @return . Expected amount of `asset` the shares represents. */ - function convertToAssets(uint256 shares) public view returns (uint256) { - // Saves an extra SLOAD if totalSupply() is non-zero. - uint256 supply = totalSupply(); - - return - supply == 0 - ? shares - : shares.mulDiv(totalAssets(), supply, Math.Rounding.Down); + function convertToAssets(uint256 shares) external view returns (uint256) { + return _convertToAssets(_strategyStorage(), shares);
What is the advantage of separating the public and private methods like this? Code paths that have the storage pointer loaded can call the internal/private versions?
tokenized-strategy
github_2023
others
69
yearn
fp-crypto
@@ -1560,7 +1560,7 @@ contract TokenizedStrategy { address _performanceFeeRecipient ) external onlyManagement { require(_performanceFeeRecipient != address(0), "ZERO ADDRESS"); - require(_performanceFeeRecipient != address(this), "Can't be self"); + require(_performanceFeeRecipient != address(this), "Can not be self");
```suggestion require(_performanceFeeRecipient != address(this), "Cannot be self"); ```
tokenized-strategy
github_2023
others
69
yearn
fp-crypto
@@ -174,7 +174,7 @@ contract AccesssControlTest is Setup { strategy.setPerformanceFeeRecipient(address(69)); vm.prank(management); - vm.expectRevert("Can't be self"); + vm.expectRevert("Can not be self");
```suggestion vm.expectRevert("Cannot be self"); ```
tokenized-strategy
github_2023
others
69
yearn
wavey0x
@@ -11,47 +11,50 @@ This makes the strategy specific contract as simple and specific to that yield g - Shares: ERC20-compliant token that tracks Asset balance in the strategy for every distributor. - Strategy: ERC4626 compliant smart contract that receives Assets from Depositors (vault or otherwise) to deposit in any external protocol to generate yield. - Tokenized Strategy: The implementation contract that all strategies delegateCall to for the standard ERC4626 and profit locking functions. -- BaseTokenizedStrategy: The abstract contract that a strategy should inherit from that handles all communication with the Tokenized Strategy contract. +- BaseStrategy: The abstract contract that a strategy should inherit from that handles all communication with the Tokenized Strategy contract. - Strategist: The developer of a specific strategy. - Depositor: Account that holds Shares
add period at the end for consistency